You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将足球实时赛事API处理得到的数组以JSON响应形式返回

解决方案

原代码存在的问题

  • request为异步回调方法,你当前封装的getData没有对外暴露处理完成的赛事数组,路由侧无法拿到数据返回给前端
  • 没有做异常捕获,API请求失败、返回体格式异常时服务会直接报错
  • 变量data未声明就使用,属于隐式全局变量,存在逻辑隐患
  • 代码里的HTML转义字符未处理,实际运行时<、"这类字符会触发语法错误

修复方案

第一步:改造封装方法为Promise异步模式

const request = require('request');

exports.getLiveMatchData = function () {
  return new Promise((resolve, reject) => {
    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': '替换为你自己的实际key',
        useQueryString: true
      }
    };

    request(options, function (error, response, body) {
      if (error) return reject(error);
      try {
        const apiRes = JSON.parse(body);
        const matchesList = apiRes.data || [];
        const liveMatches = matchesList.map(item => ({
          homeName: item.homeName,
          awayName: item.awayName,
          elapsed: item.elapsed,
          team_home_goals: item.team_home_90min_goals,
          team_away_goals: item.team_away_90min_goals,
          createdAt: Date.now()
        }));
        resolve(liveMatches);
      } catch (parseErr) {
        reject(parseErr);
      }
    });
  });
};

第二步:路由侧调用返回JSON(以Express框架为例)

const express = require('express');
const router = express.Router();
// 替换为你上面代码存放的文件路径
const matchApi = require('./matchService');

router.get('/live/matches', async (req, res) => {
  try {
    const matchList = await matchApi.getLiveMatchData();
    // 直接返回JSON格式响应
    res.json({
      code: 200,
      data: matchList,
      msg: 'success'
    });
  } catch (err) {
    console.error('获取实时赛事数据失败:', err);
    res.status(500).json({
      code: 500,
      msg: '获取赛事数据失败'
    });
  }
});

module.exports = router;

可选优化

如果后续不想用已经停止维护的request库,可以替换为axios、node-fetch等原生支持Promise的请求库,不用额外封装即可直接用async/await调用。

内容的提问来源于stack exchange,提问作者Nizar Ferchichi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 21:27:02