gpt4 book ai didi

json - 如何在 node.js 中动态读取外部 json 文件?

转载 作者:搜寻专家 更新时间:2023-10-31 23:46:29 25 4
gpt4 key购买 nike

我正在创建一个网站,该网站读取外部托管的 json 文件,然后使用 node.js 填充网站内容。

只是为了演示我所追求的,这是我在 node.js 中尝试做的事情的真正简化版本

var ids = [111, 222, 333];

ids.forEach(function(id){
var json = getJSONsomehow('http://www.website.com/'+id+'.json');

buildPageContent(json);
});

我想做的事可行吗?

(标记为“How do I return the response from an asynchronous call?”的重复,请参阅下面我的反驳评论)

最佳答案

您正在尝试同步获取它。相反,您应该瞄准的不是这样使用的函数:

var json = getJSONsomehow('http://www.website.com/'+id+'.json');

但更像这样:

getJSONsomehow('http://www.website.com/'+id+'.json', function (err, json) {
if (err) {
// error
} else {
// your json can be used here
}
});

或者像这样:

getJSONsomehow('http://www.website.com/'+id+'.json')
.then(function (json) {
// you can use your json here
})
.catch(function (err) {
// error
});

您可以使用 request 模块来获取您的数据,如下所示:

var request = require('request');
var url = 'http://www.website.com/'+id+'.json';

request.get({url: url, json: true}, (err, res, data) => {
if (err) {
// handle error
} else if (res.statusCode === 200) {
// you can use data here - already parsed as json
} else {
// response other than 200 OK
}
});

有关工作示例,请参阅 this answer .

有关详细信息,请参阅:https://www.npmjs.com/package/request

关于json - 如何在 node.js 中动态读取外部 json 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39610955/

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