【问题标题】:JSON parsing error with axios (unexpected character in server response)axios 解析 JSON 错误(服务器响应中出现意外字符)
【发布时间】:2020-06-01 08:30:00
【问题描述】:

当我尝试从服务器端点获取数据时遇到 JSON 解析错误。

Axios 首次无法自动解码 JSON 响应。

调试我的代码,我发现 Axios 在服务器响应中捕获了一些意外字符,导致 JSON 无效。

7F5
{
  "message": "OK"
  ...cut
}
0

错误:

(node:14940) UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token F in JSON at position 1

我想这可能是字符集编码问题。

axios客户端配置:

const pclClient = axios.create({
  baseURL: "http://server/endpoint",
  responseType: "json",
  responseEncoding: "utf8",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json",
    charset: "utf-8"
  }
});

使用 postman 或 Chrome 扩展高级请求客户端等工具,问题不存在。

有人可以帮我吗?

【问题讨论】:

  • 尝试删除responseEncoding , charset
  • 您以7F5 开头的消息不是有效的 JSON。
  • @haongdv。已删除,但我一直有问题。感谢您的评论。
  • 这看起来像分块的 HTTP,除了内容不是 2037 (0x7F5) 字节长。分块 HTTP 的详细信息通常应由 HTTP 客户端处理。
  • 这里很有趣。解决后请务必花时间写一个“答案”。

标签: javascript node.js json axios


【解决方案1】:

问题来自transfer-encoding: chunked响应头。

RFC 7230 告诉“接收者必须能够解析和解码分块传输 编码。”

目前,Axios 不处理分块响应 (transfer-encoding chunked not handled for application/json)

为了解决这个问题,我使用正则表达式制作了一个块解析器来删除块的信息。

const pclClient = axios.create({
  baseURL: "http://server/",
  responseType: "json",
  headers: {
    Accept: "application/json"
  }
});

const chunksParser = body => {
  return body
    .replace(/^(\w{1,3})\r\n/, "") // replace header chunks info 
    .replace(/\r\n(\w{1,3})\r\n/, "") // replace in-body chunks info
    .replace(/(\r\n0\r\n\r\n)$/, ""); // replace end chunks info
};

const getData = async () => {
  response = await pclClient.get("data.json");
  const { data } = response;
  const body = chunksParser(data);
  const json = JSON.parse(body);
  return json;
};

我一直在寻找 Axios 中的内置函数。我希望它将来可以使用。

感谢您的评论帮助我了解问题所在。

【讨论】:

    猜你喜欢
    • 2016-08-20
    • 2022-01-01
    • 2019-07-18
    • 2020-07-22
    • 1970-01-01
    • 2014-02-04
    • 2016-05-24
    • 1970-01-01
    • 2020-06-08
    相关资源
    最近更新 更多