使用Serveless framework 1.5中的lambda集成修改响应头/主体/状态代码

时间:2017-01-13 17:39:33

标签: aws-lambda serverless-framework

我使用Serveless framework 1.5。

使用“lambda-proxy integration”,修改响应头/正文/状态代码非常容易。

callback(null, {
  status: 200,
  headers: {
    'STRING_VALUE': 'STRING_VALUE'
  },
  body: 'STRING_VALUE'
});

但我想使用path_info值,所以我使用如下的serverless.yml:

functions:
  hello:
    handler: handler.hello
  events:
    - http:
        path: hello/{hi}
        method: get
        integration: lambda
        request:
          parameters:
            paths:
              hi: true

要获取path_info设置,必须使用“lambda integration”。 但我也想修改响应的响应头/正文/状态代码。 我应该如何通过“lambda integration”来设置修改这些响应值?

此致

==后记==

提交问题后,我找到了该文件: https://serverless.com/framework/docs/providers/aws/events/apigateway/#lambda-integration

据此,身体可以定制:

        response:
          headers:
            Content-Type: "'text/html'"
          template: $input.path('$')

但是,对于响应标题,文档说:

        response:
          headers:
            Content-Type: integration.response.header.Content-Type
            Cache-Control: "'max-age=120'"

我设置与上面相同,并且代码handler.js如下所示:

  callback(null, {
    header: {'Content-Type': 'image/png'}
  });

虽然标题content_type没有变成'image / png'。 如何动态修改响应头?

2 个答案:

答案 0 :(得分:2)

我自己找到了问题的答案:

要更改标题,serverless.yml设置必须为:

      response:
        headers:
          Content-Type: "integration.response.body.headers.Content-Type"
        template: $input.path('$.body')

并且响应代码必须是:

    callback(null, {
      headers: {'Content-Type': 'image/jpeg'},
      body: body
    });

一个令人困惑的问题是,“$ in response template”和“integration.response.body设置标题映射”具有相同含义。
因此,“$ .body”与“integration.response.body.body”相同。

要更改状态代码,我们应该使用Error对象。

const status = err ? new Error('[404] Not found') : null;
callback(status, {
    headers: {'Content-Type': 'image/jpeg'},
    body: body
});

答案 1 :(得分:1)

  

要获取path_info设置,必须使用" lambda integration"。

您可以使用:

使用Lambda Proxy集成访问路径参数
event["pathParameters"]["id"]

请记住首先检查event["pathParameters"] !== null是否有可能在没有任何路径参数的情况下调用Lambda。