无服务器 AWS Lambda 函数的预检 CORS 问题。

Preflight CORS issue on serverless AWS Lamba fucntions.

我尝试了 official documentation for CORS fix by serverless 及不同的解决方案,但问题仍然存在。

到目前为止我所做的是,

1,在所有函数上将 CORS 设置为 true。

 events:
  - http:
      path: /api/v1/user/login
      method: post
      cors: true

2,为 CORS 设置授权修复程序。

 GatewayResponseDefault4XX:
  Type: 'AWS::ApiGateway::GatewayResponse'
  Properties:
    ResponseParameters:
      gatewayresponse.header.Access-Control-Allow-Origin: "'*'"
      gatewayresponse.header.Access-Control-Allow-Headers: "'*'"
      gatewayresponse.header.Access-Control-Allow-Methods: "'*'"
    ResponseType: DEFAULT_4XX
    RestApiId:
      Ref: 'ApiGatewayRestApi'

3,在响应头中,我设置为,

headers: {
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*',
                "Access-Control-Allow-Headers": '*',
                'Access-Control-Allow-Credentials': true,
            }

仍然遇到基于 CORS 的问题

Error message:

Access to XMLHttpRequest at ’https://xxxxxx.execute-api.us-east-1.amazonaws.com/dev/api/v1/user/login' from origin ‘http://localhost:4200’ has
been blocked by CORS policy: Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.

Access-Control-Allow-Headers 不接受通配符。

如果您不能准确设置 header 值,只需删除 Access-Control-Allow-Headers 设置。

我不知道这是解决此问题的最佳或正确方法。 但这有效。

我将默认 cors 值更改为自定义值。

events:
- http:
  path: /api/v1/user/login
  method: post
  cors: true

对此,

events:
  - http:
      path: /api/v1/user/login
      method: post
      cors:
        origin: '*'
        headers:
          - Content-Type
          - X-Amz-Date
          - Authorization
          - X-Api-Key
          - X-Amz-Security-Token
          - X-Amz-User-Agent
          - Access-Control-Allow-Origin 
          - Access-Control-Allow-Credentials
          - Access-Control-Allow-Methods
          - Access-Control-Allow-Headers
        allowCredentials: true
        cacheControl: 'max-age=600, s-maxage=600, proxy-revalidate'

成功了!