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

AWS API Gateway调用Lambda遇认证缺失及内部错误,求正确调用方式

问题分析与解决方案

1. "Missing Authentication Token" 错误说明

你调用的根路径 https://xxxxxrv9.execute-api.us-east-1.amazonaws.com/test 未在API Gateway中配置对应的资源和方法,API Gateway无法匹配到有效请求路径,因此返回该错误。这属于正常行为——你的SAM模板仅为 /batch 路径配置了GET方法,根路径无对应配置。

若需要根路径也能响应,可在Lambda的Events节点下新增根路径配置:

Events:
  MyDemoAPI:
    Type: Api
    Properties:
      RestApiId: !Ref MyApiGateway
      Path: /batch
      Method: GET
  RootAPI: # 新增根路径配置
    Type: Api
    Properties:
      RestApiId: !Ref MyApiGateway
      Path: /
      Method: GET

2. "Internal server error" 错误修复

该错误核心原因是Lambda返回格式不符合API Gateway要求。API Gateway要求Lambda必须返回包含statusCode、body等字段的JSON对象,而你的代码直接返回数字类型的状态码,导致API Gateway无法解析响应。

修改Lambda代码如下:

const https = require("https");
const url = "https://aws.amazon.com/";

exports.handler = async function (event) {
  try {
    const statusCode = await new Promise((resolve, reject) => {
      https.get(url, (res) => {
        resolve(res.statusCode);
      }).on("error", (e) => {
        reject(e);
      });
    });
    console.log(statusCode);
    // 返回符合API Gateway规范的响应格式
    return {
      statusCode: 200, // 可自定义响应状态码,或使用获取到的statusCode
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        awsStatus: statusCode,
        message: "请求成功"
      })
    };
  } catch (error) {
    // 捕获异常并返回标准错误响应
    return {
      statusCode: 500,
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        error: error.message
      })
    };
  }
};

修改要点:

  • 用try/catch捕获请求异常,避免无处理的报错导致服务中断
  • 返回对象必须包含statusCode、headers、body三个核心字段
  • body需为字符串类型,通过JSON.stringify转换对象实现

3. 验证步骤

  1. 重新部署SAM应用:执行sam deploy --guided或对应部署命令更新Lambda与API Gateway配置
  2. 再次调用https://xxxxxrv9.execute-api.us-east-1.amazonaws.com/test/batch,此时应返回格式正确的JSON响应

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 02:13:15