来自来源 'http://localhost:8080' 的 AWS API 网关已被 CORS 策略阻止

AWS API GATEWAY from origin 'http://localhost:8080' has been blocked by CORS policy

我正在尝试部署一个要在前端使用的 API。它在单独测试 API 时有效,但在 Vue 应用程序中集成时它是 return CORS 错误,其中错误 return 是:

Access to XMLHttpRequest at 'https://APIDomain/development/pin' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我正在使用无服务器部署这个 API 我已经设置了这个 serverless.yml 中允许的来源:

service: test-lambda-node
provider:
  name: aws
  runtime: nodejs12.x
  stage: development
  region: ap-east-1
  memorySize: 512
  timeout: 15
functions:
  app:
    handler: lambda.handler
    events:
      - http:
          path: /
          method: ANY
          cors:
            origin: 'http://localhost:8080'
            headers:
              - Content-Type
              - X-Amz-Date
              - Authorization
              - X-Api-Key
              - X-Amz-Security-Token
              - X-Amz-User-Agent
            allowCredentials: false
      - http:
          path: /{proxy+}
          method: ANY
          cors:
            origin: 'http://localhost:8080'
            headers:
              - Content-Type
              - X-Amz-Date
              - Authorization
              - X-Api-Key
              - X-Amz-Security-Token
              - X-Amz-User-Agent
            allowCredentials: false

我也在使用通配符来允许所有类型的来源,但它仍然不起作用。我还尝试在 AWS API 网关控制台中手动启用 CORS,但仍然无法正常工作。 有什么方法可以让这个 API 为任何来源启用 CORS 策略?

问题

CORS header 未从您的 Vue 应用程序发送。

解决方案

在向 API 发送请求时将 Access-Control-Allow-Origin header 添加到您的 Vue 应用程序。

备注

此外,如果您使用 cookie,请将 serverless.yml 中的 allowCredentials 和 Vue 应用中的 Access-Control-Allow-Credentials 设置为 true

参考资料

Serverless - CORS 生存指南:https://www.serverless.com/blog/cors-api-gateway-survival-guide