无服务器API网关Lambda中的CORS策略阻止的资源,即使已设置



我使用的是Serverless,我有一个可通过API网关使用的lambda。像许多提到类似堆栈的COR问题一样,我在从浏览器进行调用时遇到了以下错误(通常的Postman/curl本地测试效果很好(:

Access to XMLHttpRequest at 'https://<gatewayUrl>/dev/login/?userType=userA' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field z-client-timezone is not allowed by Access-Control-Allow-Headers in preflight response
  • 集成请求类型为Lambda_Proxy

  • Cors已启用,添加了选项方法

  • lambda处理程序返回预期的标头

  • axios请求发送一个自定义标头Z-Client-Timezone,这在Lambda 中也是允许的

  • 我什么都试过了,包括这里的一切,但没有运气。

我非常沮丧,所以任何帮助都会很棒。还有一件事,当我做curl -i -X OPTIONS https://<gatewayUrl>/dev/login时,我得到了这个结果,它似乎缺少Z-Client-Timezone:

HTTP/2 200
content-type: application/json
content-length: 0
date: Fri, 10 Jul 2020 04:00:10 GMT
x-amzn-requestid: <aws_requestId>
access-control-allow-origin: *
access-control-allow-headers: Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token
x-amz-apigw-id: <apigw-id>
access-control-allow-methods: OPTIONS,POST
via: 1.1 <id>.cloudfront.net (CloudFront), 1.1 <id>.cloudfront.net (CloudFront)
x-amz-cf-pop: DFW50-C1
x-cache: Miss from cloudfront
x-amz-cf-pop: DFW55-C1
x-amz-cf-id: <cf-id>

我的Lambda:

export async function login(event) {
const headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true
}
....
return {
statusCode: 200,
headers,
body: JSON.stringify(session)
};
}

我的无服务器yml:

login:
handler: dist/src/handlers/auth.login
events:
- http:
path: login
method: post
cors: 
origin: '*'
headers:
- Access-Control-Allow-Credentials
resources:
Resources:
GatewayResponseDefault4XX:
Type: 'AWS::ApiGateway::GatewayResponse'
Properties:
ResponseParameters:
gatewayresponse.header.Access-Control-Allow-Origin: "'*'"
gatewayresponse.header.Access-Control-Allow-Headers: "'*'"
ResponseType: DEFAULT_4XX
RestApiId:
Ref: 'ApiGatewayRestApi'

我希望你能给我任何帮助。我省略了一些代码,因为除了cors的东西之外,其他的都可以工作,所以我只包含了这些代码,但如果需要更多的澄清,我很乐意提供。

虽然lambda函数允许Z-Client-Timezone标头,但AWS的内置选项方法不允许。

为了实现这一点,您可以执行以下操作-

login:
handler: dist/src/handlers/auth.login
events:
- http:
path: login
method: post
cors: 
origin: '*'
headers:
- Access-Control-Allow-Credentials
- Z-Client-Timezone

然后添加您正在发送的任何其他标头。

最新更新