使用SAM Local启动TypeScript/Node.js本地API遇启动失败求助
SAM本地运行TypeScript/Node.js API时exit status 129错误修复
错误信息
26 Apr 2024 00:43:22,108 [ERROR] (rapid) Init failed error=Runtime exited with error: exit status 129 InvokeID= 26 Apr 2024 00:43:22,109 [ERROR] (rapid) Invoke failed error=Runtime exited with error: exit status 129 InvokeID=3506a416-5cd1-42a3-ba56-45ffa76d2369 26 Apr 2024 00:43:22,110 [ERROR] (rapid) Invoke DONE failed: Sandbox.Failure
你的SAM模板配置(存在问题版)
GetAuthenticatedUserDetailsFunction: CodeUri: ../ Handler: GetAuthenticatedUserDetails.lambdaHandler Events: GetAuthenticatedUserDetails: Type: Api Properties: RestApiId: !Ref api Path: /gaud Method: get Policies: - Version: '2012-10-17' Statement: - Effect: Allow Action: "rds-db:connect" Resource: !Sub 'arn:aws:rds-db:${AWS::Region}:${AWS::AccountId}:dbuser:${DBProxyPRXID}/*' Metadata: BuildMethod: esbuild BuildProperties: Minify: true Target: es2020 Sourcemap: true EntryPoints: - src/GetAuthenticatedUserDetails.ts
核心问题及修复步骤
1. 修正Metadata的缩进层级
你的Metadata配置与函数同级,SAM无法识别该函数的构建规则,导致esbuild编译逻辑不生效。需要将Metadata缩进为GetAuthenticatedUserDetailsFunction的子属性,同时补充指定Node.js运行时版本:
GetAuthenticatedUserDetailsFunction: CodeUri: ../ Handler: src/GetAuthenticatedUserDetails.lambdaHandler # 同步修正Handler路径 Runtime: nodejs18.x # 指定与本地匹配的Node.js版本 Events: GetAuthenticatedUserDetails: Type: Api Properties: RestApiId: !Ref api Path: /gaud Method: get Policies: - Version: '2012-10-17' Statement: - Effect: Allow Action: "rds-db:connect" Resource: !Sub 'arn:aws:rds-db:${AWS::Region}:${AWS::AccountId}:dbuser:${DBProxyPRXID}/*' Metadata: # 缩进至函数内部,让SAM识别构建规则 BuildMethod: esbuild BuildProperties: Minify: true Target: es2020 Sourcemap: true EntryPoints: - src/GetAuthenticatedUserDetails.ts
2. 用编译后的产物启动本地服务
sam build会将TypeScript代码编译为JavaScript并输出到.aws-sam/build目录,直接用原始模板启动会指向未编译的TS文件,导致运行时错误。执行以下命令:
sam build sam local start-api --template .aws-sam/build/template.yaml
3. 确保Handler路径匹配编译产物
esbuild会根据EntryPoints生成同名.js文件:
- 若
EntryPoints为src/GetAuthenticatedUserDetails.ts,编译后会生成src/GetAuthenticatedUserDetails.js,因此Handler需设为src/GetAuthenticatedUserDetails.lambdaHandler - 若想简化路径,可在
BuildProperties中添加OutDir: dist,将编译产物统一输出到dist目录,此时Handler设为dist/GetAuthenticatedUserDetails.lambdaHandler
额外排查点
- 本地Node.js版本需与Lambda运行时版本一致(比如模板指定
nodejs18.x,本地就用v18.x版本) - 检查
sam build过程中是否有编译错误,若esbuild提示依赖缺失,需安装对应依赖
内容的提问来源于stack exchange,提问作者Magnus Lidman
相关产品推荐
相关产品推荐

