在Serverless Framework 1.0中如何使用路径参数

20

我想使用路径参数/customer/{customerId}来发起GET请求,以便使用AWS Lambda查询客户:

functions:
  createCustomer:
    handler: handler.createCustomer
    events:
    - http:
        path: customer
        method: post
  readCustomer:
    handler: handler.readCustomer
    events:
    - http:
        path: customer
        method: get

我该如何定义路径参数以便在使用Serverless Framework 1.0时将其传递给我的AWS Lambda函数?

3个回答

46

在 serverless.yml 中进行定义。

readCustomer:
  handler: handler.readCustomer
  events:
    - http:
        path: customer/{customerId}
        method: get

在代码中访问 customerId

const customerId = event.pathParameters.customerId;

请注意,它在 'event.pathParameters' 中,因为使用 AWS Lambda 代理集成时,API Gateway 将整个客户端请求映射到后端 Lambda 函数的输入 'event' 参数中,如 https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format 所述。 - jarmod

3
更改路径名称
path: customer/{customerId}

更改您的handler.js文件

module.exports.createCustomer= function(event, context) {

{ message: 'Go Serverless v1.0! Your function executed successfully!', event }

// you can write your logic here


};

1
我可以创建可用的资源!但是路径参数似乎没有传递给Lambda函数...我收到了一个“message”:“提供的关键元素与模式不匹配” - Marcel
请再检查一遍。如果想要使用某个数据库注册客户,您可以在这里编写代码。 - Niroshan Ranapathi
谢谢,有了你的帮助我刚刚解决了这个问题! - Marcel

-3

# 解决方案

  1. serverless.yml中定义路径参数,例如customerId:

path: customer/customerId

  1. 在API Gateway下的API /customer/{customerId}中,进入Integration Request并创建一个新的Body Mapping Template,响应application/json并具有以下内容:

{ "customerId": "$input.params('customerId')" }

现在,路径参数customerId将作为JSON事件传递到AWS Lambda函数中:

{
  "input": "{\"customerId\":\"marcel@example.com\"}",
  "response": {
    "Item": {
      "password": "abc#123",
      "email": "marcel@example.com"
    }
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接