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

AWS前端接收Lambda返回值异常求助:Amplify+API Gateway配置排查

前端通过AWS Amplify调用API Gateway返回空值且状态码异常的解决方法

问题描述

我有一个简单应用,前端部署在AWS Amplify,通过API Gateway调用返回字符串的Lambda函数。用curl测试API Gateway时能正常获取Lambda返回的statusCode=222及响应体,说明Lambda和API Gateway本身功能正常。

前端使用以下fetch代码调用接口:

fetch(`${apiGatewayUrl}${resourcePath}`, {
  method: 'GET',
  headers: {
   'Content-Type': 'application/json',
   'Authorization': `Bearer ${authToken}`
    // Add any additional headers if required for authentication or other purposes
  },
})
.then(response => {
  alert (`response:: ${response.status}`)
  if (!response.ok) {
    throw new Error(`HTTP error! Status: ${response.status}`);
  }
  
  alert('Raw response:', response);
  return response.json();
})
.then(data => {
  // Process the data returned from the API
  console.log('API response:', data);
  alert('data:: ', JSON.stringify(data));
})
.catch(error => {
  alert (`Error: ${error}`);
  console.error('Error:', error);
});

其中${apiGatewayUrl}${resourcePath}配置正确,和curl使用的地址完全一致。但前端执行代码时,响应状态码是API Gateway默认的200,且返回值为空。目前已配置CORS,API Gateway的方法请求、集成请求、集成响应、方法响应均保持默认设置。


解决步骤

1. 修正Lambda返回格式

API Gateway默认要求Lambda返回标准JSON结构,直接返回纯字符串会导致网关无法正确解析,进而返回空值。修改Lambda代码,确保返回结构符合要求:

Python示例:

import json

def lambda_handler(event, context):
    return {
        'statusCode': 222,
        'headers': {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'  # 可与API Gateway的CORS配置保持一致
        },
        'body': json.dumps("你的返回字符串")  # 必须将字符串转为JSON格式的body
    }

Node.js示例:

exports.handler = async (event) => {
    return {
        statusCode: 222,
        headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify("你的返回字符串")
    };
};

2. 检查API Gateway集成响应映射

默认的集成响应映射可能无法适配自定义返回结构,需手动确认映射模板:

  • 进入API Gateway控制台,找到对应方法,切换到集成响应标签
  • 选择目标状态码(如222),查看application/json类型的映射模板
  • 确保模板内容为$input.path('$'),或根据Lambda返回结构调整,保证能正确提取body内容

3. 调整前端响应解析方式

如果Lambda返回的是纯字符串而非JSON对象,前端用response.json()解析会失败,导致返回空值。临时替换解析方式测试:

.then(response => {
  alert (`response:: ${response.status}`)
  if (!response.ok) {
    throw new Error(`HTTP error! Status: ${response.status}`);
  }
  
  alert('Raw response:', response);
  return response.text(); // 替换为text解析
})
.then(data => {
  console.log('API response:', data);
  alert('data:: ', data); // 直接显示字符串内容
})

如果此方法能拿到正确值,说明问题出在返回格式的JSON解析上,需回到步骤1调整Lambda返回结构。

4. 验证Authorization头的影响

前端携带的Authorization头可能触发API Gateway的认证逻辑(如Cognito),若认证配置异常,会导致网关返回默认200空响应。可临时注释该头测试:

// 'Authorization': `Bearer ${authToken}`

若去掉后响应正常,需检查authToken有效性,以及API Gateway的授权设置(如Cognito用户池)是否允许当前用户访问目标资源。

5. 查看API Gateway执行日志

开启CloudWatch日志排查请求流程:

  • 进入API Gateway控制台,找到目标API,点击设置标签
  • 开启CloudWatch日志,设置日志级别为INFO
  • 重新发起前端请求,到CloudWatch控制台查看日志,确认请求是否到达Lambda、Lambda返回值是否正常、API Gateway是否正确处理响应

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 11:52:50