node.js - 为什么我无法使用 Nodejs 检索 json 数据?
问题描述
我只需要一种从特定 url 检索 json 数据的方法。我写了这个程序:
'use strict';
var http = require('http');
var request = require("request");
var url = "https://restcountries.eu/rest/v2/name/united"
var server = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
res.write(JSON.parse(body)) // Print the json response
}else{
res.write("error");
res.end();
}
})
})
server.listen(1338, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1338/');
但我得到了这个错误:
# node mytest.js
Server running at http://127.0.0.1:1338/
undefined:1
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
^
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at Request._callback (/home/xxx/Nodejs/Esempi/emilianotest2.js:18:25)
at Request.self.callback (/home/xxx/Nodejs/Esempi/node_modules/request/request.js:185:22)
at Request.emit (events.js:160:13)
at Request.<anonymous> (/home/xxx/Nodejs/Esempi/node_modules/request/request.js:1161:10)
at Request.emit (events.js:160:13)
at IncomingMessage.<anonymous> (/home/xxx/Nodejs/Esempi/node_modules/request/request.js:1083:12)
at Object.onceWrapper (events.js:255:19)
at IncomingMessage.emit (events.js:165:20)
at endReadableNT (_stream_readable.js:1101:12)
为什么?
编辑:
如果我删除 JSON.parse,这是我得到的错误:
Server running at http://127.0.0.1:1338/
_http_outgoing.js:651
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'first argument',
^
TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string or Buffer
at write_ (_http_outgoing.js:651:11)
at ServerResponse.write (_http_outgoing.js:626:10)
解决方案
因为您提供了参数json: true
,request
所以已经为您解析了它。然后,当您将 not-JSON-any-more 数组传递给 时JSON.parse
,它会在解析之前变成一个字符串;数组中的对象得到了熟悉的[object Object]
表示,并且JSON.parse
因为[object Object]
看起来不像一个正确的数组而窒息。
try {
let json = JSON.stringify([{a:1}])
console.log("parsed once:");
console.log(JSON.parse(json));
console.log("parsed twice:");
console.log(JSON.parse(JSON.parse(json)));
} catch(e) {
console.error(e.message);
}
编辑:当你删除时JSON.parse
,你最终会尝试res.write
一个对象。res.write
不喜欢那样(正如 Roland Starke 在评论中已经注意到的那样);它会更喜欢一个字符串:
res.write(JSON.stringify(body))
推荐阅读
- javascript - 如何增加/减少点击 Js/ReactJs 中相同按钮的计数
- r - 基于两行的另一个数据框过滤数据
- android - 我收到了这个找不到的消息语音(没有这样的文件或目录)
- apache-spark - SparkSQL 在第一次出现字符串时拆分字符串
- list - Haskell:飞镖游戏
- powershell - 为什么我在这段代码中使用了太多的磁盘空间?
- javascript - 使用 jQuery .when,如何传入可变数量的函数调用?
- java - 如何为这种工厂模式使用 Guice Assisted Inject?
- java - Room SQL:使用两个表上的 WHERE 参数查询具有一对多关系的对象
- python - 名称“ImageDataBunch”未定义