【问题标题】:Use path params in serverless framework 1.0在无服务器框架 1.0 中使用路径参数
【发布时间】:2016-12-30 01:40:25
【问题描述】:

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

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

我必须如何定义路径参数才能使用 无服务器框架 1.0 将其传递给我的 AWS Lambda 函数?

【问题讨论】:

    标签: amazon-web-services aws-lambda serverless-framework


    【解决方案1】:

    在 serverless.yml 中定义

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

    在代码中访问customerId

    const customerId = event.pathParameters.customerId;
    

    【讨论】:

    【解决方案2】:

    更改路径名

    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
    
    
    };
    

    【讨论】:

    • 我可以创建资源,这行得通!但是路径参数似乎没有传递给 Lambda 函数......我收到一条“消息”:“提供的关键元素与架构不匹配”
    • 再次检查。如果想使用某些数据库注册客户,您可以在这里编写代码
    • 谢谢你,在你的帮助下我刚刚解决了这个问题!
    【解决方案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"
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-25
      • 1970-01-01
      • 1970-01-01
      • 2020-09-08
      • 1970-01-01
      • 2022-07-19
      • 2019-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多