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

如何通过AWS SAM启动API并向Node.js Handler传递参数?

解决方案

你的问题核心有两个:一是launch.json存在语法格式错误,二是Lambda函数获取API参数的方式不符合API Gateway触发的Lambda事件结构。以下是针对GET和POST请求的具体配置及代码调整方案:

1. 修正launch.json基础格式

你提供的launch.json中configurations数组内的配置项缺少外层大括号,先修正这个语法问题:

{
    "configurations": [
        {
            "type": "aws-sam",
            "request": "direct-invoke",
            "name": "my-example:Function",
            "invokeTarget": {
                "target": "api",
                "templatePath": "template.yaml",
                "logicalId": "ApiFunction"
            },
            "lambda": {
                "runtime": "nodejs16.x"
            },
            "sam": {},
            "api": {
                "path": "/api",
                "httpMethod": "get"
            }
        }
    ]
}

2. GET请求传参配置与Lambda代码调整

配置launch.json添加查询参数

在api节点下新增queryStringParameters字段,定义需要传递的GET参数:

"api": {
    "path": "/api",
    "httpMethod": "get",
    "queryStringParameters": {
        "id": "123",
        "name": "test"
    }
}

修改Lambda函数获取参数

API Gateway触发的Lambda中,GET查询参数存储在event.queryStringParameters而非event.params,调整代码:

exports.handler = async (event) => {
    // 获取GET查询参数
    const params = event.queryStringParameters;
    console.log('GET参数:', params); // 输出: { id: '123', name: 'test' }
    
    // 业务逻辑...
    return {
        statusCode: 200,
        body: JSON.stringify(params)
    };
};

3. POST请求传参配置与Lambda代码调整

第一步:修改template.yaml添加POST事件(可选,仅部署后需要支持POST时配置)

在ApiFunction的Events下新增POST类型的API事件:

Events:
  Get:
    Type: Api
    Properties:
      Path: '/api'
      Method: get
  Post:
    Type: Api
    Properties:
      Path: '/api'
      Method: post

第二步:配置launch.json添加POST请求体

将httpMethod改为post,并新增requestBody字段:

"api": {
    "path": "/api",
    "httpMethod": "post",
    "requestBody": {
        "id": 456,
        "content": "post-test"
    }
}

修改Lambda函数获取POST参数

POST请求的JSON体存储在event.body中,需要先解析为JSON对象:

exports.handler = async (event) => {
    // 解析POST请求体
    const params = JSON.parse(event.body);
    console.log('POST参数:', params); // 输出: { id: 456, content: 'post-test' }
    
    // 业务逻辑...
    return {
        statusCode: 200,
        body: JSON.stringify(params)
    };
};

验证调试

完成上述配置和代码修改后,启动VS Code调试,即可在Lambda函数中获取到对应的GET/POST参数。调试时可通过VS Code的调试控制台输出,确认参数是否正确传递。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 03:22:38