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

如何通过aws-sdk的lambda.invoke调用Serverless Express的POST路由?

通过AWS Lambda.invoke调用Express POST路由的正确方式

问题

我使用Serverless框架将Node/Express API部署到单个AWS Lambda函数中,需要直接从JavaScript调用其中的/api/v5.1/points POST路由。现有代码结构如下:

Node/Express Serverless应用

const express = require("express");
const awsServerlessExpress = require("aws-serverless-express");
const app = express();
const server = awsServerlessExpress.createServer(app)
...

const pointsRoute = require("./src/routes/points.route");

...

app.use(`/api/v5.1/points`, pointsRoute);


module.exports.handler = (event, context) => {
   
    awsServerlessExpress.proxy(server, event, context);
}

points.route.js

const express = require("express");
const router = express.Router();

const { postPoints } = require("../ctrls/points.ctrl.js");

router.route("/").post(postPoints);

module.exports = router;

points.ctrl.js

exports.postPoints = (req, res, next) =>  {
    console.log("hitting postPoints method");
    ...
    ...
}

我尝试用aws-sdk的lambda.invoke编写调用函数,但默认会发起GET请求,导致路由不存在。添加GET路由后能成功返回,但我需要调用POST路由。尝试添加httpMethod: "POST"或嵌套http对象均触发验证错误,请问如何正确发起POST请求命中对应路由?

解决方案

你需要按照API Gateway事件标准格式构造Payload参数,aws-serverless-express依赖该格式解析请求方法、路径和请求体。正确的调用代码如下:

const AWS = require("aws-sdk");

AWS.config.update({
      accessKeyId: "id",
      secretAccessKey: "AccessKey",
      region: "region"
})

const lambda = new AWS.Lambda();

export const invokeLambda = async (points: any) => {
    return lambda.invoke({
        FunctionName: 'my-lambda-fn',
        InvocationType: 'RequestResponse',
        Payload: JSON.stringify({
          httpMethod: "POST",
          path: "/api/v5.1/points",
          body: JSON.stringify(points),
          headers: {
            "Content-Type": "application/json"
          }
        }),
      }).promise();
}

核心说明

  • httpMethod必须作为顶层字段放在Payload中,不能嵌套,这是API Gateway事件的规范,aws-serverless-express会读取该字段判定请求方法。
  • 添加Content-Type: application/json请求头,确保Express的express.json()中间件能正确解析请求体(若你的应用配置了该中间件)。
  • 之前的验证错误是因为Payload格式不符合API Gateway事件标准,按上述方式构造即可触发目标POST路由。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 04:23:20