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.
Join my free course on the basics of Flask-SQLAlchemy: https://prettyprinted.com/flasksql
thank you it was simple and perfect !
2:15 – you might find Ctrl+/ helpful. Also, thanks for the great tutorial!
Sadly this doesn't do the job for me 🙁
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?
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].
You deserve my like, thanks <3
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."
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!
Duudeee!!!!! Thankyouuuuu!!!!!!!!! Neeedddeeddd Thiiiisss Very very very very muchhhh!!!
hey, cors isn't letting flask_jwt_extended create those authentication cookies. Please help!!
Awesome thank you so much
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.."
Thanks a ton for this video!
Excellent video… thanks!
What about if we want to deploy ngnix and flask kn same server, ? Then how to setup flask cors
THANK YOU SO MUCH.
Great! Great video!!! Thank you very much!
Amazing explanation. Thank you so much.
Thanks!