【问题标题】:Preflight CORS issue on serverless AWS Lamba fucntions.无服务器 AWS Lambda 函数的预检 CORS 问题。
【发布时间】:2018-12-04 12:34:41
【问题描述】:

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

到目前为止,我所做的是,

1、在所有函数上设置 CORS 为真。

 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.

【问题讨论】:

  • 这似乎是正确的。有时,当您的后端返回 internal server error 时,会返回 CORS 错误。顺便说一句,您是否缺少在 access-control-allow 字段中添加 OPTIONS
  • 在您的前端 JavaScript 代码中,删除您添加的将 Access-Control-Allow-Origin 设置为请求标头的任何部分。

标签: node.js cors serverless-framework aws-serverless


【解决方案1】:

我不知道这是解决此问题的最佳方法还是正确方法。 但这行得通。

我将默认 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'

它成功了!

【讨论】:

    【解决方案2】:

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

    如果您无法准确设置标头值,只需删除 Access-Control-Allow-Headers 设置即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-22
      • 2018-03-19
      • 1970-01-01
      • 2018-08-27
      • 2019-02-24
      • 1970-01-01
      • 2018-06-25
      • 2021-10-07
      相关资源
      最近更新 更多