【发布时间】: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