NodeJS SyntaxError:JSON 中的意外标记位于位置 0

ora*_*int 12 json response authorize.net node.js

body从Authorize.net的沙盒API的响应是:

{
  "messages": {
    "resultCode": "Error",
    "message": [
      {
        "code": "E00012",
        "text": "You have submitted a duplicate of Subscription 5777085. A duplicate subscription will not be created."
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

但是当我去解析它时:

try {
   bodyObj = JSON.parse(body);
} catch (ex) {
   console.error(ex);
}
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

语法错误:JSON 中位置 0 的意外标记

和这个: console.log(response.headers['content-type']);

返回这个: application/json; charset=utf-8

我究竟做错了什么?我想将 JSON 解析为 JS 对象。

smi*_*s15 14

其实你没看到,但是有一个看不见的unicode字符,特别是JSON开头的字节序标记。
由于字节顺序标记不是有效的 JSON 字符,因此 JSON.parse 拒绝了它。
字节顺序标记图像
要删除,请使用以下代码。

function removeByteOrderMark(str){
    return str.replace(/^\ufeff/g,"")
}
// OR (faster),
let removeByteOrderMark = a=>a[0]=="\ufeff"?a.slice(1):a
Run Code Online (Sandbox Code Playgroud)