带有CORS的Flask服务静态文件夹

问题描述 投票:0回答:1

在我的前端应用程序中,我试图访问我在静态文件夹中提供的文件,但是CORS出现问题。我看到的问题是

Access to XMLHttpRequest at 'http://127.0.0.1:5000/static_folder/apple.xml' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我的后端Flask应用具有以下设置

app = Flask(__name__, static_url_path='/static_folder', static_folder="static_folder")

似乎我需要在返回文件时在响应中添加'Access-Control-Allow-Origin'标头。 Flask是否有全局的设置方式?

我尝试使用flask_cors,但未成功完成

from flask_cors import CORS, cross_origin
app = Flask(__name__, static_url_path='/static_folder', static_folder="static_folder")
CORS(app)

通过将CORS标头设置为[],我可以使用SimpleHTTPRequestHandler获得类似的功能>

def end_headers (self):
        self.send_header('Access-Control-Allow-Origin', '*')
        SimpleHTTPRequestHandler.end_headers(self)

但是我想使用flask完成此任务,而不是启动简单的http服务器。

在我的前端应用程序中,我试图访问我在静态文件夹中提供的文件,但是CORS出现问题。我看到的问题是在http://127.0.0.1:5000 / ...]上对XMLHttpRequest的访问

在cors(app)之后添加以下行:
@ app.after_requestdef after_request(回应):response.headers.add('Access-Control-Allow-Headers','Content-Type,Authorization')response.headers.add('Access-Control-Allow-Methods','GET,POST,PATCH,DELETE,OPTIONS')返回响应
python flask cors static-files
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.