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

NodeJS中无法读取/解析Riot API Match v5返回结果问题

解决Riot Match v5 API响应解析undefined及JSON.parse报错问题

问题根源

Node.js的https.get通过data事件返回响应时,是分块传输的——每次触发data事件只返回部分数据片段,不是完整的JSON内容。你直接在data事件里访问d.info.gameDuration(此时d是Buffer或部分字符串,不是解析后的对象),以及直接对片段执行JSON.parse,自然会出现undefined和解析报错。

修正代码

要先把所有数据块收集完整,再做解析和字段访问:

function getMatch(matchId, puId) {
  const https = require('node:https');

  // 用来累加所有响应数据块
  let rawData = '';

  https.get(`https://americas.api.riotgames.com/lol/match/v5/matches/${matchId}?api_key=${riotApiKey}`, (resp) => {
    // 每收到一块数据就追加到rawData里
    resp.on('data', (chunk) => {
      rawData += chunk;
    });

    // 所有数据接收完成后,再处理解析
    resp.on('end', () => {
      try {
        const matchResults = JSON.parse(rawData);
        // 现在可以正常访问字段了
        console.log(matchResults.info.gameDuration);
      } catch (err) {
        console.error('JSON解析失败:', err.message);
      }
    });

    // 捕获请求过程中的错误
    resp.on('error', (err) => {
      console.error('请求API出错:', err.message);
    });
  });
}

关键注意点

  • 必须在end事件中处理完整数据,data事件只负责收集片段
  • 增加try/catch包裹JSON.parse,方便排查解析失败的具体原因
  • 用模板字符串拼接URL比+号更易读和维护

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 11:42:35