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.

from flask_cors import CORS

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

 

Then in your routes import cross_origin and decorate routes to allow requests from certain origins.

from flask_cors import cross_origin

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

 

Or like this if you have 2 or more origins.

@cross_origin(origins=['http://hello.example.com', 'http://world.example.com'])

 




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 6dfe00 in the box below so that we can be sure you are a human.