【问题标题】:Returning an array as a json response将数组作为 json 响应返回
【发布时间】: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


【解决方案1】:

我猜您的实际问题是如何从 getData() 函数内部返回数据。如果是这种情况,那么您只需要使用可等待的 Promise:

var request = require('request');

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,
    },
  };

  return Promise((resolve) => {
    request(options, function (error, response, body) {
      data = JSON.parse(body);
      const matchesList = data['data'];

      const liveMatches = [];
      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(),
        });
      }

      resolve(liveMatches); // <--- this is the important part
    });
  });
}

exports.data = getData();

然后你会以类似的方式使用它:

const serverData = await getData();

console.log(serverData); // OK

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-24
    • 2019-07-27
    • 2023-03-14
    • 2019-01-27
    • 2019-03-16
    • 1970-01-01
    • 2018-02-28
    • 2014-10-07
    相关资源
    最近更新 更多