首页 > 解决方案 > API 网关,被 CORS 策略阻止:没有“Access-Control-Allow-Origin”标头

问题描述

我知道这个问题可能会被重复,但现有的问题都没有指向我没有做的任何事情......

我已经使用无服务器框架部署了一个 API,但是我在使用 CORS 时遇到了问题。

我正在使用 axios 进行获取请求:

axios.get('https://test.execute-api.us-west-1.amazonaws.com/dev/test?from=2012-01-09T21:40:00Z')
     .then(response => {
       this.data = response.data;
     })
     .catch(error => console.log(error))

我收到以下错误:

Access to XMLHttpRequest at 'https://test.execute-api.us-west-1.amazonaws.com/dev/test?from=2012-01-09T21:40:00Z' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我已经做了什么:

在此处输入图像描述

此外,我的 Lambda 函数的响应返回以下标头:

return events.APIGatewayProxyResponse{
    StatusCode: http.StatusOK,
    Headers: map[string]string{
        "Access-Control-Allow-Origin":      "http://localhost:8080",
        "Access-Control-Allow-Credentials": "true",
    },
    Body: string(jsonEvents),
}, nil

我也尝试设置Access-Control-Allow-Origin'*'

我的 serverless.yml 文件包含cors: true每个函数事件:

functions:
  deploymentFrequency:
    handler: bin/update/deployment-frequency
    events:
      - http:
          path: deployment-frequency
          method: post
          cors: true
  fetchDeploymentFrequency:
    handler: bin/fetch/deployment-frequency
    events:
      - http:
          path: deployment-frequency
          method: get
          cors: true

我错过了什么?似乎没有任何效果。邮递员的请求工作正常,它看起来包括标题,所以这似乎是 OPTIONS 方法的问题。

标签: goaws-api-gatewayserverless

解决方案


我的配置是:

(event, context, callback) => {
   callback(null, {
      statusCode: (code || 200),
      body: JSON.stringify(resp),
      headers: { 'Access-Control-Allow-Origin': '*'},
   });
}

它对我来说很好。我以前和你有同样的问题,但只要你用 CORS: true 定义你的函数并且你的响应包含标题,你应该没问题。

注意:我不理解 sintax“map[string]string”,在这种情况下不需要凭据。


推荐阅读