Bootstrap FreeKB - Flask - Resolve "Access to fetch has been blocked by CORS policy"
Flask - Resolve "Access to fetch has been blocked by CORS policy"

Updated:   |  Flask articles

Let's say something like this is being returned when a web app is submitting a request to your Flask app. In this example:

  • http://foo.example.com/foo is the URL of the web app submitting the request to your Flask app
  • http://bar.example.com/bar is the URL of your Flask app that processes the request
Access to fetch at 'http://bar.example.com/bar' from origin 'http://foo.example.com/foo' 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.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

 

This error often occurs when the client URL and server URL don't match. Often, this can be resolved by allowing CORS (Cross Origin Resource Sharing).

"preflight" means that before the browser attempt the request (GET / POST / PUT / et cetera), it first sends an OPTIONS request to the server to determine if the server is opting-in to receiving a cross-origin POST that has Authorization and Content-Type: application/json headers. You should be able to replicate this with curl.

curl \
--include \ 
--request OPTIONS \
--header "Origin: http://127.0.0.1:3000" \
--header 'Access-Control-Request-Method: POST' \
--header 'Access-Control-Request-Headers: Content-Type, Authorization' \
--url https://www.example.com

 

This can almost always be resolved by install the flask-cors package using pip.

pip install flask-cors

 

And then in __init__.py import CORS and init app with CORS. This will allow requests from all origins.

from flask_cors import CORS

def app():
    app = Flask(__name__)
    CORS(app)
    return app

 

Or you can configure CORS to only accept requests from certain origins. This would apply to all of the routes in your Flask app.

from flask_cors import CORS

def app():
    app = Flask(__name__)
    CORS(app, resources={"/*": {"origins": ["https://foo.example.com", "https://bar.example.com"]}})
    return app

 

Or you can decorate routes with the @cross_origin decorator so that the route accept requests from all origins.

from flask_cors import cross_origin

@app.route('/bar', methods=['POST'])
@cross_origin()
def bar():
    return "hello world"

 

Or accept requests from certain origins.

from flask_cors import cross_origin

@app.route('/bar', methods=['POST'])
@cross_origin(origins=['http://hello.example.com', 'http://world.example.com'])
def bar():
    return "hello world"

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 1cbc96 in the box below so that we can be sure you are a human.