gpt4 book ai didi

json - 无法从 NodeJS API 调用获取 JSON

转载 作者:太空宇宙 更新时间:2023-11-04 02:16:08 24 4
gpt4 key购买 nike

我有以下 NodeJS 代码来从现有 API 端点获取 JSON 结构:

var request = require('request');

request({
url: 'http://192.168.56.101:8088/json/disc/bases'
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body);
}
});

当我 console.log(body) 时,我得到一些空的东西,而如果我直接在浏览器的选项卡中打开 URL,我清楚地得到一个答案,一个未经美化的 json 对象。

如果我尝试使用 API http://jsonplaceholder.typicode.com/posts/1例如,我没有任何困难,console.log(body) 返回预期的 json。尽管如此,我注意到 header 响应存在许多差异:而 jsonplaceholder API 在其 header 中返回 14 个元素:

enter image description here

我的 API 仅返回 3 个元素:

enter image description here

你们知道这意味着什么以及我可以做什么来获取 JSON。我研究了许多其他方法来做到这一点,但没有任何帮助。我希望你能让我摆脱我已经厌倦的魔鬼问题。谢谢!

最佳答案

我发现响应 header 有如此大的差异很奇怪。因此,我研究了这个方向,并意识到从 Chrome 和我的 NodeJS 应用程序调用相同的 API 时,请求 header 有很大不同。

请求 header 中不同的键:值之一是Connection: keep-alive。因此,我将此 header 添加到我的 NodeJS 应用程序中的请求中,现在一切正常。感谢您的帮助。

这里是最终代码:

var request = require('request');

request({
url: 'http://192.168.56.101:8088/json/disc/bases',
headers: {
'Connection': 'keep-alive'
}
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body);
}
});

关于json - 无法从 NodeJS API 调用获取 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35631502/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com