我正在对lambda服务进行REST调用,并获得包含一些预期数据以及响应标头信息的响应。我正在尝试访问客户端的标头键值之一,但是当我在javascript中读取标头信息时,我只会得到内容类型。在浏览器开发人员的“网络”标签中,我可以看到标题键值集。我试图在lambda的Cloudformation模板中为该特定密钥添加Access-Control-Expose-Headers,但是在将其部署到AWS时却遇到另一个异常。不知道我在想什么。任何帮助将非常感激。谢谢。
答案 0 :(得分:0)
请确保您在API网关的路径中具有options
方法:
Api:
Type: AWS::ApiGateway::RestApi
Properties:
Name: "my-api"
Body:
swagger: "2.0"
info:
version: "2018-03-20T13:41:34Z"
basePath: "/"
schemes:
- "https"
paths:
/my-path:
options:
responses:
"200":
headers:
Access-Control-Allow-Origin:
type: "string"
Access-Control-Allow-Methods:
type: "string"
Access-Control-Allow-Headers:
type: "string"
x-amazon-apigateway-integration:
responses:
default:
statusCode: "200"
responseParameters:
method.response.header.Access-Control-Allow-Methods: "'GET,POST,PUT,DELETE,OPTIONS'"
method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,x-api-key,x-amz-security-token,Auth'"
method.response.header.Access-Control-Allow-Origin: "'*'"
requestTemplates:
application/json: "{\"statusCode\":200}"
passthroughBehavior: when_no_match
type: mock
post:
...
您可以通过Lambda设置标题,如下所示:
exports.handler = async event => {
...
return {
isBase64Encoded: false,
statusCode: 200,
headers: {
'Access-Control-Expose-Headers': 'Content-Type,...',
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}
}