使用LocalStack与aws-cdk-local部署后访问API提示无法找到路径集成报错
LocalStack+aws-cdk-local部署后API访问NotFoundException解决方案
这个报错通常由路径格式错误、stage未发布、集成配置缺失三类问题导致,对应修复方案如下:
- 修正调用路径
LocalStack v1.x及以上版本的REST API调用需在_user_request_后追加你实际配置的接口路径,仅请求到_user_request_/会触发该报错,标准格式为:http://localhost:4566/restapis/<rest-api-id>/<stage-name>/_user_request_/<实际接口路径>
若使用LocalStack v2+版本,更推荐使用无需_user_request_的简化路径:http://<rest-api-id>.execute-api.localhost.localstack.cloud:4566/<stage-name>/<实际接口路径> - 校验stage发布状态
先通过awslocal apigateway get-rest-apis确认你使用的rest-api-id正确,再执行以下命令校验指定stage是否已发布:
若查询结果为空,说明cdk-local部署时未自动发布stage,可手动执行发布命令:awslocal apigateway get-deployments --rest-api-id <替换为你的rest-api-id>awslocal apigateway create-deployment --rest-api-id <替换为你的rest-api-id> --stage-name <替换为你的stage名> - 校验集成绑定配置
执行命令查看API下所有路径的集成配置:
确认你请求的路径和请求方法(GET/POST等)已经绑定了对应的集成(Lambda/HTTP等)。若缺失对应配置,检查CDK代码是否正确配置了路径和方法的集成,注意需要开启API的自动部署配置,示例:awslocal apigateway get-resources --rest-api-id <替换为你的rest-api-id>import * as apigateway from 'aws-cdk-lib/aws-apigateway'; import * as lambda from 'aws-cdk-lib/aws-lambda'; const helloLambda = new lambda.Function(this, 'HelloHandler', { runtime: lambda.Runtime.NODEJS_18_X, code: lambda.Code.fromAsset('lambda'), handler: 'hello.handler' }); const api = new apigateway.RestApi(this, 'testApi', { deploy: true, // 开启自动部署,避免stage未发布问题 stageName: 'prod' }); // 给根路径绑定GET方法的Lambda集成 api.root.addMethod('GET', new apigateway.LambdaIntegration(helloLambda)); - 其他排查点
确认LocalStack容器的4566端口已正常映射,未使用自定义端口;社区版LocalStack不支持部分API Gateway高级特性,若使用了专业版特性也会触发该报错。
内容的提问来源于stack exchange,提问作者Michael Kedem
相关产品推荐
相关产品推荐

