首页 > 解决方案 > “不存在'Access-Control-Allow-Origin'标头”对于某些请求但不是其他请求的错误

问题描述

我有一个在 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)设置为示例。有了这个,我希望基本上任何请求都有 CORS 标题,所以我不会有任何策略阻止我的前端请求。

理想的情况是只允许来自 的请求https://app.myvuejsapp.net,所以我尝试使用CORS(app, support_credentials=True, origins=['https://app.myvuejsapp.net'])但也没有成功。

我还尝试使用CORS(myblueprint)每个.py路由文件为我的每个蓝图制作一个 CORS 实例(每个蓝图都有一个),但也没有成功。

奇怪的是,我在 Vue 上确实有一个功能可以在应用程序运行mounted良好时运行。我看不出此功能与其他不起作用的功能之间有任何区别。

工作功能示例(返回truefalse从后端返回):

      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 存储桶权限配置?

谢谢。

标签: pythonvue.jsamazon-s3flaskcors

解决方案



推荐阅读