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

Resource blocked by CORS policy in Serverless API Gateway Lambda even though its set up

我正在使用无服务器并且我有一个可通过 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

我非常沮丧,所以任何帮助都会很棒。还有一件事,当我做 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)
    };
}

我的Serverless.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 header,但 AWS 的 built-in 选项方法不允许。

为了允许这样做,您可以执行以下操作 -

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

然后添加您要发送的任何其他 header。