简体   繁体   中英

Flask serving static folder with CORS

In my frontend app I'm trying to access a file I'm serving in a static folder but I'm getting an issue with CORS. The issue I'm seeing is

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.

My backend Flask app has the following set

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

It seems that I need to add the 'Access-Control-Allow-Origin' header to my responses when returning the files. Does Flask have a global way to set this?

I've tried using flask_cors but haven't been successful with

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

I was able to get something similar working with the SimpleHTTPRequestHandler by setting the CORS headers as

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

But I'd like to use flask to accomplish this rather than starting a simple http server.

after cors(app) add these lines:

@app.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type, Authorization')
    response.headers.add('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE, OPTIONS')
    return response

Also, if using the flask-cors package, you should be able to blanket your static requests:

from flask import Flask
from flask_cors import CORS

# Initialize
app = Flask(__name__)
cors = CORS(app, resources={r"/static/*": {"origins": "*"}})

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM