基于aws-nodejs-typescript模板的Serverless-offline POST接口无响应问题
问题排查解决步骤
1. 优先检查Lambda Handler代码逻辑
aws-nodejs-typescript模板默认生成的handler如果被修改过,很容易因为没有正确返回响应导致请求挂起,请确认你的handler.ts(或对应入口文件)的hello函数符合以下要求:
- 若使用async写法,必须显式return符合APIGatewayProxy结构的响应对象
- 若使用callback写法,必须显式调用callback返回结果
示例正确代码:
import type { APIGatewayProxyHandler, APIGatewayProxyResult } from 'aws-lambda'; export const hello: APIGatewayProxyHandler = async (event): Promise<APIGatewayProxyResult> => { // 必须处理body解析的异常,避免解析失败抛出未捕获错误导致挂起 const name = event.body ? JSON.parse(event.body)?.name ?? 'World' : 'World'; return { statusCode: 200, headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ message: `Hello ${name}`, }), }; };
2. 验证插件版本兼容性
serverless-offline与serverless-webpack的高版本经常出现兼容问题,可先替换为稳定版本组合验证:
- 修改package.json中的依赖版本:
"devDependencies": { "serverless-offline": "^8.8.1", "serverless-webpack": "^5.9.1" }
- 删除node_modules和package-lock.json后重新执行
npm install
3. 补充serverless.ts配置项
在provider节点添加API Gateway解析配置,避免body解析失败导致请求挂起:
const serverlessConfiguration: AWS = { service: 'your-service-name', frameworkVersion: '3', provider: { name: 'aws', runtime: 'nodejs16.x', // 新增以下配置 apiGateway: { binaryMediaTypes: ['*/*'], }, }, plugins: ['serverless-webpack', 'serverless-offline'], // 其余配置保持不变 }
4. 验证请求配置
Postman发送请求时必须添加请求头Content-Type: application/json,否则body无法被正常解析会导致逻辑阻塞。你也可以先直接调用Lambda直调地址http://localhost:3000/2015-03-31/functions/hello/invocations发送POST请求,判断是Handler逻辑问题还是API Gateway模拟层的问题:
- 若直调地址有响应:说明是serverless-offline的API网关模拟层配置问题,启动时可添加参数
serverless offline --stage dev --noAuth绕过权限校验 - 若直调地址无响应:则是Handler逻辑存在未捕获异常或无返回值的问题
内容的提问来源于stack exchange,提问作者André
相关产品推荐
相关产品推荐

