【发布时间】:2021-11-20 16:46:15
【问题描述】:
所以我使用的是足球直播比赛 api
我从 json 响应中获取我需要的内容并将其存储在一个数组中
当我访问某个路线时,我想将数组作为 json 响应返回
这是代码
var request = require('request');
exports.data = function getData(){
const options = {
method: 'GET',
url: 'https://elenasport-io1.p.rapidapi.com/v2/inplay',
qs: {page: '1'},
headers: {
'x-rapidapi-host': 'elenasport-io1.p.rapidapi.com',
'x-rapidapi-key': 'mykey',
useQueryString: true
}
};
request(options, function (error, response, body) {
var liveMatches = [];
data = JSON.parse(body);
var matchesList = data['data'];
for(let i = 0; i < matchesList.length; i++){
liveMatches.push(
{
homeName : matchesList[i]['homeName'],
awayName : matchesList[i]['awayName'],
elapsed : matchesList[i]['elapsed'],
team_home_goals : matchesList[i]['team_home_90min_goals'],
team_away_goals : matchesList[i]['team_away_90min_goals'],
createdAt : Date.now()
}
);
}
for (let j= 0; j<liveMatches.length;j++){
console.log(liveMatches[j]);
console.log("--------------------------------------------");
}
});
}
【问题讨论】:
-
return是什么意思?您正在使用的request函数有一个回调函数,它不会向其调用者返回值,因此您使用希望该函数接收的数据运行该函数。如果您愿意,使用the node version of the fetch API 是一个更好的主意。另外,为什么要发送 JSON 而不是实际的 JS 数据? JSON适用于当您需要打包并将JS对象数据从JS发送到其他东西时。只要你在 JS,不要把任何东西变成 JSON。 -
还有什么问题?这是一项非常常见的任务,因此您应该能够在 WWW 或 SO 上找到解决方案。
-
JSON.stringify('liveMatches')?
标签: javascript node.js json