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

API Gateway GET仅根路径生效,资源路径返回404问题求助

API Gateway新增资源路径返回404问题排查

问题场景

使用AWS CDK创建API Gateway与Lambda集成服务时,根路径/的GET请求可正常调用Lambda,但新增的/getgenerictournaments路径的GET请求返回404,二者使用同一Lambda函数。

代码片段

const getGenericTournamentsLambdaFn = new lambda.Function(this, 'GetGenericTournamentsLambda', {
  functionName: "GetGenericTournaments",
  runtime: lambda.Runtime.NODEJS_16_X,
  code: lambda.Code.fromAsset("../src"),
  handler: "get_generic_tournaments.handler",
  environment: {
  }
});

const api = new apigateway.RestApi(this, "ATPPredictionsService", {
  restApiName: "ATPPredictionsService",
  description: "Provides APIs for saving and fetching API predictions"
});

// 正常工作的根路径GET方法
api.root.addMethod('GET', new apigateway.LambdaIntegration(getGenericTournamentsLambdaFn, {
  requestTemplates: { "text/html": '{ "statusCode": "200"}' }
}));

// 返回404的资源路径GET方法
const getGenericTournamentsResource = api.root.addResource('getgenerictournaments');
getGenericTournamentsResource.addMethod('GET', new apigateway.LambdaIntegration(getGenericTournamentsLambdaFn, {
  requestTemplates: { "text/html": '{ "statusCode": "200"}' }
}));

常见原因及解决方法

1. 调用URL缺少阶段前缀

API Gateway部署后默认会绑定一个阶段(如prod),所有资源请求必须包含阶段前缀才能正确路由:

  • 错误示例:https://{api-id}.execute-api.{region}.amazonaws.com/getgenerictournaments
  • 正确示例:https://{api-id}.execute-api.{region}.amazonaws.com/prod/getgenerictournaments

2. CDK部署未生效或资源未同步

  • 重新执行cdk deploy命令,确保部署过程无报错,新资源已成功同步到API Gateway
  • 登录AWS控制台,进入API Gateway服务,确认getgenerictournaments资源已存在且GET方法配置正确

3. 路径大小写不匹配

检查实际请求的路径大小写是否与代码中定义的getgenerictournaments完全一致,API Gateway路径区分大小写。

4. 集成权限配置异常(概率较低)

虽然CDK的LambdaIntegration会自动生成API Gateway调用Lambda的权限,但仍可检查Lambda函数的IAM角色,确认是否包含允许API Gateway触发的策略。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 05:35:18