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

Leave a Reply

40 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@prettyprinted
2 hours ago

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

@foxedex447
2 hours ago

thank you it was simple and perfect !

@maxchornyi9837
2 hours ago

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

@Robin-xm4us
2 hours ago

Sadly this doesn't do the job for me 🙁

@yomajo
2 hours 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
2 hours 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
2 hours ago

You deserve my like, thanks <3

@bhushukoli3837
2 hours 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
2 hours 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
2 hours ago

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

@rishitkurup2298
2 hours ago

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

@aqibfayyaz1619
2 hours ago

Awesome thank you so much

@pahehepaa4182
2 hours 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
2 hours ago

Thanks a ton for this video!

@Allen-by6ci
2 hours ago

Excellent video… thanks!

@rookiefirecycle1754
2 hours ago

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

@mrigankpawagi
2 hours ago

THANK YOU SO MUCH.

@louispapa0101
2 hours ago

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

@olask7343
2 hours ago

Amazing explanation. Thank you so much.

@AhmedKhaled-xp7dm
2 hours ago

Thanks!

40
0
Would love your thoughts, please comment.x
()
x