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

JavaScript中调用API返回对象属性值为undefined的问题排查

问题原因与解决方案

你遇到的问题核心是API返回的JSON数据被当成字符串处理,导致无法直接访问对象属性。

具体原因

你使用了response.text()方法,它会把API返回的内容以原始字符串形式返回。虽然控制台打印时看起来像对象,但本质是一串字符,自然没有content、name这类对象属性,所以访问时输出undefined。

修复方法

把response.text()替换为response.json(),这个方法会自动将API返回的JSON字符串解析成JavaScript对象,之后就能正常访问属性了。

修改后的完整代码

const url = "https://quotes15.p.rapidapi.com/quotes/random/";
const options = {
  method: "GET",
  headers: {
    "X-RapidAPI-Key": "api_key",
    "X-RapidAPI-Host": "quotes15.p.rapidapi.com",
  },
};
(async function main() {
  try {
    const response = await fetch(url, options);
    // 替换为json()解析成可操作的JS对象
    const result = await response.json();
    console.log(result);
    // 现在可以正常访问属性
    console.log(result.content);
    console.log(result.originator.name);
  } catch (error) {
    console.error(error);
  }
})();

补充说明

  • response.text():获取原始响应字符串,适用于非JSON格式的内容(比如纯文本、HTML)。
  • response.json():专门用于解析JSON格式的响应,直接返回可操作的JS对象,是调用JSON API时的标准做法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 01:52:40