Cross-Origin Resource Sharing in Flask

Posted by


CORS (Cross-Origin Resource Sharing) is a security feature implemented in web browsers to restrict the requests made by a web page to resources in another domain. This is to prevent malicious websites from stealing data or performing actions on behalf of the user without their consent.

In this tutorial, we will discuss how to implement CORS in a Flask application. Let’s get started:

Step 1: Install Flask-CORS
To start, you will need to install the Flask-CORS extension. You can do this by running the following command in your terminal:

pip install Flask-CORS

Step 2: Configure CORS in your Flask application
Next, you need to add the CORS configuration to your Flask application. In your app.py file, import the CORS module and configure it as follows:

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

This will enable CORS for all routes in your Flask application. If you want to configure CORS for specific routes, you can do so by passing the allowed origins, methods, and headers as arguments to the CORS function:

CORS(app, resources={r"/api/*": {"origins": "http://localhost:3000"}})

This configuration allows requests from the http://localhost:3000 origin to access routes under the /api/ path.

Step 3: Testing the CORS configuration
To test the CORS configuration, you can create a simple route in your Flask application and make a request to it from a different domain.

@app.route('/api/data', methods=['GET'])
def get_data():
    return {'message': 'Hello, World!'}

You can then make a request to this route from a different domain using a tool like Postman or by creating a simple HTML page with JavaScript:

fetch('http://localhost:5000/api/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log(error))

If CORS is configured correctly, you should see the response from the server in the console.

Step 4: Additional CORS Configuration
You can further customize the CORS configuration by setting additional options such as allowing credentials, exposing headers, and setting preflight options.

CORS(app, resources={r"/api/*": {"origins": "http://localhost:3000"}},
     supports_credentials=True,
     allow_headers=["Content-Type", "Authorization"],
     expose_headers=["Content-Type", "Authorization"],
     methods=["GET", "POST"],
     max_age=3600)

These options allow credentials to be sent with requests, specify which headers to expose in the response, set the allowed methods, and cache the preflight response for 1 hour.

That’s it! You have now successfully implemented CORS in your Flask application. Remember to test your application thoroughly to ensure that CORS is working as expected and to avoid any security vulnerabilities.

0 0 votes
Article Rating
40 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@prettyprinted
1 month ago

Join my free course on the basics of Flask-SQLAlchemy: https://prettyprinted.com/flasksql

@foxedex447
1 month ago

thank you it was simple and perfect !

@maxchornyi9837
1 month ago

2:15 – you might find Ctrl+/ helpful. Also, thanks for the great tutorial!

@Robin-xm4us
1 month ago

Sadly this doesn't do the job for me 🙁

@yomajo
1 month ago

In 4:40 we can clearly see both index.html and app.py are in the same folder (location), so why did CORS issue arise in the first place?

@thuggfrogg
1 month ago

If you're trying to do this on a mac with your localhost and this still doesn't work, it's probably because your 5000 port is being used by AirPlay. Disable it! Settings -> Sharing -> AirPlay [disable].

@antoniobento6813
1 month ago

You deserve my like, thanks <3

@bhushukoli3837
1 month ago

Import "flask_cors" could not be resolvedPylance(reportMissingImports)
I am getting this error in VSCode. How should I resolve this? I also tried pip install but it said that : "'pipenv' is not recognized as an internal or external command,

operable program or batch file."

@anubhavpanfer6069
1 month ago

It helped a lot. I was gonna break my screen as I was continuously looking for how to deploy flask files online. And at last after 5 hours when I was able to deploy everything this problem came before me. Thanks a lot for helping and saving my screen lmao. Great explanation indeed!

@aryanpanwar6399
1 month ago

Duudeee!!!!! Thankyouuuuu!!!!!!!!! Neeedddeeddd Thiiiisss Very very very very muchhhh!!!

@rishitkurup2298
1 month ago

hey, cors isn't letting flask_jwt_extended create those authentication cookies. Please help!!

@aqibfayyaz1619
1 month ago

Awesome thank you so much

@pahehepaa4182
1 month ago

Why is flask-cors not working ? Still getting this error "..has been blocked by CORS policy: 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 disable.."

@pranavab4455
1 month ago

Thanks a ton for this video!

@Allen-by6ci
1 month ago

Excellent video… thanks!

@rookiefirecycle1754
1 month ago

What about if we want to deploy ngnix and flask kn same server, ? Then how to setup flask cors

@mrigankpawagi
1 month ago

THANK YOU SO MUCH.

@louispapa0101
1 month ago

Great! Great video!!! Thank you very much!

@olask7343
1 month ago

Amazing explanation. Thank you so much.

@AhmedKhaled-xp7dm
1 month ago

Thanks!