【问题标题】:NodeJS get request. JSON.parse: unexpected tokenNodeJS 获取请求。 JSON.parse:意外令牌
【发布时间】:2016-02-05 15:04:01
【问题描述】:

我正在用 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);
    });
}

你能帮帮我吗?

提前感谢您的帮助。

【问题讨论】:

  • 与您的示例 URL 一起工作得很好(除了body.stringfy() 抛出错误)。不过,您并没有检查是否真的从服务器返回了 JSON 响应(通过检查 Content-Type 标头)。

标签: json node.js httprequest


【解决方案1】:

将响应连接为字符串可能存在编码问题,例如如果每个块的缓冲区在开头或结尾都转换为带有部分 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。

【讨论】:

  • 使用setEncoding() 将确保多字节序列不会被截断,正如here 所记录的那样。
  • @AndréLuiz 正如 robertklep 所述,这可能不会导致您的特定问题,但是在上面第 1 行的第一个示例中给出了声明。 Buffer.concat() 不断用前一个缓冲区的串联替换该缓冲区收到块。
  • 刚刚工作。谢谢!我只需要注释行 res.setEncoding('utf8');正如 robertklep 所说的
  • @AndréLuiz 有趣的案例,因为 robertklep 有资格辩称 res.setEncoding("utf-8") 正在阻止您的初始方法因我假设的问题而受到影响。所以,让你的脚本工作的任何东西都可能与其他东西有关......但谁在乎它现在是否工作。
猜你喜欢
  • 1970-01-01
  • 2014-12-07
  • 1970-01-01
  • 2014-06-06
  • 2014-12-04
  • 2018-08-09
  • 2017-10-13
  • 2019-04-01
  • 1970-01-01
相关资源
最近更新 更多