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

调用API时返回Undefined:AWS Amplify网站数据传输问题排查

排查API Gateway返回Undefined的问题

从几个核心方向逐一排查:

1. 先确认API响应的实际结构

你当前直接取JSON.parse(result).body,但大概率API返回的结构里没有body字段,或者响应格式和预期不符。先修改代码打印原始响应,明确返回内容:

fetch("https://0vuhroulyh.execute-api.eu-north-1.amazonaws.com/dev", requestOptions)
  .then(response => response.text())
  .then(result => {
    console.log("API原始返回内容:", result);
    alert(result);
  })
  .catch(error => {
    console.log('请求错误:', error);
    alert('请求失败:' + error.message);
  });

如果API返回的是直接业务数据(比如{"calcResult": 100}),那之前取.body自然会得到undefined。

2. 改用正确的响应解析方式

如果API返回JSON格式,直接用response.json()解析更稳妥,避免二次转换:

fetch("https://0vuhroulyh.execute-api.eu-north-1.amazonaws.com/dev", requestOptions)
  .then(response => {
    // 先校验请求是否成功
    if (!response.ok) {
      throw new Error(`请求失败,状态码:${response.status}`);
    }
    return response.json();
  })
  .then(result => {
    console.log("解析后的响应:", result);
    // 根据实际结构取值,比如result.calcResult或直接result
    alert(result.calcResult || result);
  })
  .catch(error => {
    console.error('错误详情:', error);
    alert('请求出错:' + error.message);
  });

3. 确认输入参数是否正确传递

在callAPI函数开头添加打印,检查输入值是否正常:

var callAPI = (unit1, unit2, wcka, unit3, unit4, scka) => {
  console.log("收到的输入参数:", unit1, unit2, wcka, unit3, unit4, scka);
  // 后续代码不变...
}

如果某个参数是undefined,说明对应的输入框ID写错,或者输入框不存在,导致document.getElementById('xxx').value拿不到值,传给API后触发后端异常,返回不符合预期的内容。

4. 检查跨域(CORS)配置

打开浏览器开发者工具(F12)查看「网络」标签:

  • 若出现403或跨域相关错误,需在API Gateway控制台开启CORS,允许Amplify网站域名访问。
  • 若为5xx状态码,说明后端(如Lambda)执行出错,去Lambda控制台查看日志排查。

5. 检查后端(Lambda)的返回格式

如果API Gateway对接Lambda,Lambda必须返回符合要求的格式:

// Lambda示例返回格式
exports.handler = async (event) => {
  const response = {
    statusCode: 200,
    headers: {
      "Access-Control-Allow-Origin": "*" // 或指定你的Amplify域名
    },
    body: JSON.stringify({ result: "计算结果" }) // 业务数据需放在body中并转成字符串
  };
  return response;
};

若Lambda直接返回普通对象(如return { result: 123 }),API Gateway会包装成异常结构,导致前端解析出错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 13:07:50