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

Node.js开发Discord Bot调用API报Cannot read property '0' of undefined错误

错误原因
  • 核心问题:你对StandingsList的访问逻辑写在了try...catch块外部,当API返回的结构不符合预期时,代码直接抛出异常不会被捕获,所以出现了Cannot read property '0' of undefined的报错。你之前正常运行的results命令是把所有访问返回字段的逻辑都放在了try块里,异常会被捕获自然不会直接抛错。
  • 触发原因:大概率是你调用driverstandings命令时传入的赛季参数args[2]无效(比如参数为空、输入了不存在的赛季编号),导致API返回的StandingsTable下没有StandingsList字段,该字段为undefined,访问其索引0自然报错。
  • 隐藏问题:你当前只判断了请求的error参数,没有校验HTTP响应状态码,若接口返回404、500等错误状态,返回的body结构不符合预期也会触发解析错误。
解决方法
  1. 把所有访问API返回JSON字段的逻辑全部移入try块内,确保异常能被捕获。
  2. 可以增加字段存在性校验,也可以使用ES6可选链操作符?.简化空值判断逻辑,避免空值报错。
  3. 新增HTTP响应状态码校验,只有状态码为200时才进行JSON解析和后续逻辑处理。
修正后代码示例
case 'driverstandings':                 
    request('http://ergast.com/api/f1/'+args[2]+'/driverStandings.json', (error, response, body) => {
        if(error) {
            msg.reply(error);
            return;
        }
        // 新增响应状态码校验
        if(response.statusCode !== 200) {
            msg.reply('请求接口失败,请检查输入参数是否合法');
            return;
        }
        const temp = JSON.parse(body);
        let answer = '';
        try {
            // 所有字段访问移入try块
            answer = 'Season: ' + temp.MRData.StandingsTable.StandingsList[0].round;
            for(var i = 0; i < temp.MRData.StandingsTable.StandingsList[0].DriverStandings.length; i++) {
                answer += (i+1)+'. ' 
                    + temp.MRData.StandingsTable.StandingsList[0].DriverStandings[i].Driver.givenName +' '
                    + temp.MRData.StandingsTable.StandingsList[0].DriverStandings[i].Driver.familyName + ', ' 
                    + temp.MRData.StandingsTable.StandingsList[0].DriverStandings[i].points +' points, wins: '
                    + temp.MRData.StandingsTable.StandingsList[0].DriverStandings[i].wins +'\n';
            }
        }catch(error) {
            console.log(error);
            answer = 'No entries,请检查输入的赛季参数是否正确';
        }   
        msg.reply(answer);
    });
    break;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 10:27:01