NodeJS 获取请求。 JSON.parse:意外标记

NodeJS get request. JSON.parse: unexpected token

我正在用 NodeJS 编写一个函数,它命中 Url 并检索它的 json。但我在 JSON.parse 中遇到错误:意外标记。

在 json 验证器中,当我从浏览器复制并粘贴到文本字段时,字符串通过了测试,但是当我粘贴 Url 以便解析器获取 json 它显示一条无效消息。

我想这是响应编码的问题,但我无法弄清楚它是什么。这里如果我的函数有一个例子 Url.

function getJsonFromUrl(url, callback)
{
    url = 'http://steamcommunity.com/id/coveirao/inventory/json/730/2/';

    http.get(
        url
        , function (res) {
        // explicitly treat incoming data as utf8 (avoids issues with multi-byte chars)
        res.setEncoding('utf8');

        // incrementally capture the incoming response body
        var body = '';
        res.on('data', function (d) {
            body += d;
        });

        // do whatever we want with the response once it's done
        res.on('end', function () {
            console.log(body.stringfy());
            try {
                var parsed = JSON.parse(body);
            } catch (err) {
                console.error('Unable to parse response as JSON', err);
                return callback(err, null);
            }

            // pass the relevant data back to the callback
            console.log(parsed);
            callback(null, parsed);
        });
    }).on('error', function (err) {
        // handle errors with the request itself
        console.error('Error with the request:', err.message);
        callback(err, null);
    });
}

你能帮帮我吗?

在此先感谢您的帮助。

将响应连接为字符串可能存在编码问题,例如如果每个块的缓冲区都转换为在开头或结尾带有部分 UTF-8 编码的字符串。因此,我建议首先连接为缓冲区:

var body = new Buffer( 0 );
res.on('data', function (d) {
  body = Buffer.concat( [ body, d ] );
});

当然,代表您将缓冲区显式转换为字符串可能会有所帮助,而不是依赖 JSON.parse() 隐式执行此操作。如果使用不寻常的编码,这可能是必不可少的。

res.on('end', function () {
  try {
    var parsed = JSON.parse(body.toString("utf8"));
  } catch (err) {
    console.error('Unable to parse response as JSON', err);
    return callback(err, null);
  }
        ...

除此之外,给定 URL 提供的内容似乎非常有效 JSON。