Aws lambda 动态访问控制允许源标头无服务器
我配置了一个无服务器功能,如下所示Aws lambda 动态访问控制允许源标头无服务器,aws-lambda,cors,aws-api-gateway,amazon-cloudfront,serverless,Aws Lambda,Cors,Aws Api Gateway,Amazon Cloudfront,Serverless,我配置了一个无服务器功能,如下所示 id: handler: id.get events: - http: path: id method: get cors: origin: "" headers: - Content-Type - X-Amz-Date - Authorization
id:
handler: id.get
events:
- http:
path: id
method: get
cors:
origin: ""
headers:
- Content-Type
- X-Amz-Date
- Authorization
- X-Api-Key
- X-Amz-Security-Token
- x-access-token
allowCredentials: true
我的处理函数中的代码如下
let headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': event.headers.Origin ? event.headers.Origin : event.headers.origin,
'Access-Control-Allow-Credentials': true
}
callback(null, {
"isBase64Encoded": false,
"statusCode": 200,
"headers": headers,
"body": JSON.stringify(body),
"multiValueHeaders": multiValueHeaders
})
我收到对选项请求的响应
access-control-allow-origin: *
access-control-allow-credentials: true
因此,我得到以下错误
访问位于“”的XMLHttpRequesthttps://example.com/dev/id“起源”http://localhost:8080'已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:当请求的凭据模式为'include'时,响应中'access control Allow Origin'标头的值不得为通配符'*'。XMLHttpRequest启动的请求的凭据模式由withCredentials属性控制
我希望访问控制允许来源
应该是动态的(请求的来源),我如何解决这个问题?我用下面的代码创建了一个新方法选项
module.exports.options = async (event, context, callback) => {
const origin = event.headers.Origin || event.headers.origin;
context.succeed({
headers: {
"Access-Control-Allow-Headers": "Accept,Accept-Language,Content-Language,Content-Type,Authorization,x-correlation-id,x-access-token",
"Access-Control-Allow-Methods": "GET,HEAD,OPTIONS",
"Access-Control-Allow-Origin": origin ? origin : '*',
"Access-Control-Allow-Credentials": true
},
statusCode: 204
});
};
serverless.yml
options:
handler: id.options
events:
- http:
path: id
method: options
更改此配置:
身份证件:
处理程序:id.get
活动:
-http:
路径:id
方法:获取
cors:
来源:“*”
标题:
-内容类型
-X-Amz-Date
-授权书
-X-Api-Key
-X-Amz-Security-Token
-x-access-token
allowCredentials:true请格式化代码。