【发布时间】:2019-10-12 20:47:28
【问题描述】:
我有一个在 S3 上运行的 VueJS 应用程序,它由在 AWS Elastic Beastalk 上运行的 Flask 驱动的 API 提供服务。
问题
当发出 一些 请求时,我得到以下信息:
Access to XMLHttpRequest at 'https://api.myflaskapi.net/blueprint/get_info?date=2019-01-01' from origin 'https://app.myvuejsapp.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
到目前为止我做了什么
在我的__init__.py 文件中,由Flask 中的应用程序工厂初始化,我将CORS(app, support_credentials=True) 设置为this link 上的示例。有了这个,我希望基本上任何请求都有 CORS 标题,所以我不会有任何策略阻止我的前端请求。
理想的情况是只允许来自https://app.myvuejsapp.net 的请求,所以我尝试使用CORS(app, support_credentials=True, origins=['https://app.myvuejsapp.net']),但也没有成功。
我还尝试使用CORS(myblueprint) 为每个.py 路由文件为我的每个蓝图创建一个CORS 实例(每个蓝图都有一个),但也没有成功。
奇怪的是,我在 Vue 上确实有一个功能,它在应用程序为 mounted 时运行,效果很好。我看不出这个和其他不起作用的功能有什么区别。
工作函数示例(从后端返回true 或false):
checkDB() {
const path = this.base_url + 'blueprint/check_db'
axios.get(path, this.token)
.then(checkupd => {
this.isupdated = Boolean(checkupd.data);
if (this.isupdated == true) {
this.update_msg = "Database up to date."
this.loading = false
this.finished = true
} else {
this.update_msg = "WARNING: Check DB status."
}
})
.catch(error => {
console.log(error)
})
},
非工作函数示例(从后端返回 XLS):
getSalesFrom(file) {
const fs = require('fs')
const FileDownload = require('js-file-download');
const path = this.base_url + `blueprint/get_sales?date=${this.date}`
axios.get(path, {
headers:
{
"X-Access-Token": "mytoken",
"Content-Type": "application/json"
},
responseType: 'blob'
})
.then(response => {
const content = response.headers['content-type'];
download(response.data, 'text.xlsx', content)
})
.catch(error => {
console.log(error)
})
this.export_dialog = false
}
S3 CORS 配置 XML
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>Authorization</AllowedHeader>
<AllowedHeader>Content-Length</AllowedHeader>
<AllowedHeader>Access-Control-Allow-Origin</AllowedHeader>
<AllowedHeader>X-Access-Token</AllowedHeader>
</CORSRule>
</CORSConfiguration>
关于我可能做错了什么有什么想法吗? 我已经阅读了一段时间,但似乎无法找到解决这个看似非常简单的问题的方法......也许我应该弄乱 S3 存储桶权限配置?
谢谢。
【问题讨论】:
-
你能试试这个cors = CORS(app, resources={r"/*": {"origins": "app.myvuejsapp.net"}})
-
Nothing...同样的错误 - 还尝试在原点前面添加
https。 -
现在我看到您正在发送自定义标头和您的请求,那么您可以尝试将 'Access-Control-Request-Headers': '*' 添加到您的响应标头中吗?
-
是的,我使用
X-Access-Token发送我的令牌(不知道这是否是一个好方法,但它是目前的样子)。 @onuriltan,不知道该怎么做,有什么链接可以指导我如何添加吗?
标签: python vue.js amazon-s3 flask cors