Setting http response header from AWS lambda

[亡魂溺海] 提交于 2019-11-26 23:13:22

问题


My API Gateway/Lamdba setup returns an http response header: Lamdba uses callback function to return the value as part of a json and the Integration Response maps it into a header (using integration.response.body)

With this solution, the values are sent back both in the body and the header.

How can I map headers from the Lambda response without duplicating the values in the response body?


回答1:


If you have Lambda proxy integration enabled, you can set the response headers as part of Lambda output and API Gateway will return them as part of the HTTP response to the client.

Node.js example:

callback(null, {
    "isBase64Encoded": false, // Set to `true` for binary support.
    "statusCode": 200,
    "headers": {
        "header1Name": "header1Value",
        "header2Name": "header2Value",
    },
    "body": "...",
});

where headers can be null or unspecified if no extra response headers are to be returned.

See Output Format of a Lambda Function for Proxy Integration.




回答2:


and, if you DON'T have Lamba proxy integration enabled, you can add (and map) the response headers in the amazon API gateway console:

go to resources -> method execution -> method response -> add 'Access-Control-Allow-Origin' (or whatever) header for http status 200. Then go back to method execution -> method integration -> http status 200 -> set header mapping for 'Access-Control-Allow-Origin' to '*' (or whatever).

Solved this error...: "No 'Access-Control-Allow-Origin' header is present on the requested resource"




回答3:


Since the question states that custom mappings are being used (using integration.response.body), it means Lambda Proxy Integrations are NOT being used. So, the solution, in this case, is to map the headers the way you are already doing.

To remove the headers duplication from the body part, use mapping template in the integration response and ignore headers in the mapping. I think you might be using pass through responses, that's why you are seeing duplicate headers.

See more documentation here: https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html



来源:https://stackoverflow.com/questions/43190935/setting-http-response-header-from-aws-lambda

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!