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

基于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的高版本经常出现兼容问题,可先替换为稳定版本组合验证:

  1. 修改package.json中的依赖版本:
"devDependencies": {
  "serverless-offline": "^8.8.1",
  "serverless-webpack": "^5.9.1"
}
  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é

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 04:06:05