【发布时间】:2021-06-04 18:57:59
【问题描述】:
我正在尝试从我的 VueJS 应用程序调用 AWS 托管 API,该应用程序在我的 localhost:8080 上运行。我用this blog post 来设置vue.config.js 这个块:
module.exports = {
devServer: {
proxy: 'https://0123456789.execute-api.eu-west-1.amazonaws.com/'
},
...
}
有了这个,我可以使用此代码向该主机上的端点发出GET 请求:
this.$axios
.get('https://0123456789.execute-api.eu-west-1.amazonaws.com/mock/api/endpoint',
{
headers: {
'Content-Type': 'application/json'
}})
这是因为我已将 AWS API Gateway 模拟端点配置为为 OPTIONS 方法返回这些标头:
Access-Control-Allow-Headers: 'Cache-Control,Expires,Pragma,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'
Access-Control-Allow-Methods: 'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT'
Access-Control-Allow-Origin: '*'
但是,我无法拨打此电话:
this.$axios
.get('https://0123456789.execute-api.eu-west-1.amazonaws.com/lambda/api/function',
{
headers: {
'Content-Type': 'application/json'
}})
此端点是一个 Lambda 集成,还有一个 OPTIONS 方法,其标头与上述相同。
为什么配置相同的两个端点对 axios 有不同的响应?
更新
按照@deniz 的建议,我已更新.env.development 文件以包含:
VUE_APP_API_URI=https://0123456789.execute-api.eu-west-1.amazonaws.com/
我还将axios 请求更新为:
let url = 'mock/api/endpoint'
let headers = {
headers: {
'Content-Type': 'application/json',
},
}
this.$axios
.get(url, headers)
...和...
let url = 'lambda/api/function'
let headers = {
headers: {
'Content-Type': 'application/json',
},
}
this.$axios
.get(url, headers)
第一个GET 请求得到的结果是:
200 OK
但是第二个请求的响应是:
Access to XMLHttpRequest at 'https://0123456789.execute-api.eu-west-1.amazonaws.com/lambda/api/function' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
【问题讨论】:
标签: amazon-web-services vue.js axios cors aws-api-gateway