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

调用Roblox Games API获取游戏信息时遇数据读取异常求助

解决Roblox Games API数据读取undefined问题

问题概述

调用Roblox Games API获取游戏信息时,读取response.data[0]返回undefined,读取response.data[0].id提示id未定义,但手动请求API返回的JSON结构明明包含预期数据。

核心原因

Roblox的部分API会拦截缺少合法User-Agent头的请求,返回非JSON格式内容(如验证页面),导致response.data并非预期的包含数组的对象,自然无法读取到data[0]。

解决步骤

  1. 添加合法请求头:在axios请求中加入模拟浏览器的User-Agent,避免被Roblox拦截。
  2. 完善错误捕获:打印完整响应内容,排查实际返回的数据结构。
  3. 优化代码写法:统一使用async/await搭配try/catch,避免await和.then()混用导致逻辑混乱。

修改后的代码示例

const axios = require("axios");

module.exports = {
    name: "info",
    execute: async (bot, message, args) => {
        try {
            const response = await axios.get("https://games.roblox.com/v1/games?universeIds=3759152694", {
                headers: {
                    // 添加模拟浏览器的User-Agent
                    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
                }
            });
            
            // 先打印完整响应数据确认结构
            console.log("完整响应数据:", JSON.stringify(response.data, null, 2));
            
            // 读取目标数据前做边界判断
            if (response.data.data && response.data.data.length > 0) {
                const gameInfo = response.data.data[0];
                console.log("游戏ID:", gameInfo.id);
                console.log("游戏名称:", gameInfo.name);
            } else {
                console.log("未获取到有效游戏数据");
            }
        } catch (error) {
            // 捕获并打印错误详情
            console.error("请求失败:", error.message);
            if (error.response) {
                console.error("响应状态码:", error.response.status);
                console.error("响应内容:", error.response.data);
            }
        }
    },
};

关键说明

  • 必须添加User-Agent:Roblox API会对无UA的请求做反爬处理,返回非预期内容。
  • 先验证响应结构:打印完整的response.data,确认是否和手动获取的JSON结构一致,避免因返回内容不符导致读取错误。
  • 增加边界判断:检查response.data.data是否存在且不为空数组,避免直接读取data[0]导致报错。

内容的提问来源于stack exchange,提问作者not enough dinos

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 18:33:36