go - 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.
我已经做了什么:
- 确保 API Gateway 中有一个 OPTIONS 方法,其方法响应如下所示:
- 确保我部署了这些更改。
此外,我的 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 方法的问题。
解决方案
我的配置是:
(event, context, callback) => {
callback(null, {
statusCode: (code || 200),
body: JSON.stringify(resp),
headers: { 'Access-Control-Allow-Origin': '*'},
});
}
它对我来说很好。我以前和你有同样的问题,但只要你用 CORS: true 定义你的函数并且你的响应包含标题,你应该没问题。
注意:我不理解 sintax“map[string]string”,在这种情况下不需要凭据。
推荐阅读
- time-complexity - 为什么我们不能在比较排序算法中比 O(n log n) 时间更快地对 N 个数字进行排序?
- firebase - 我应该如何从根本上提高flutter应用性能?
- tensorflow - 使用 Keras 进行图像着色 - val_loss 振荡
- python - 从 OpenCV-python 中的视频中保存感兴趣的帧
- r - ShinyDashboard 无法创建动态绘图
- python - 如何使用子进程保存输出并在终端中查看输出?
- openlayers - OpenLayers 跳过加载高于特定分辨率的矢量特征
- haskell - Haskell 无论是主要
- c++ - 为什么多进程 C++ gRPC 服务器不起作用?
- android - 如何在单击“onbackpressed”时将动画添加到片段