Enabling CORS (Cross-Origin Resource Sharing) in Flask

Posted by

Enable CORS with Flask

Enable CORS (Cross-Origin Resource Sharing) with Flask

If you are building a web application using Flask and need to make requests to a different domain, you may encounter Cross-Origin Resource Sharing (CORS) issues. By default, browsers restrict requests made from one domain to another for security reasons. However, you can enable CORS in your Flask application to allow cross-origin requests.

How to Enable CORS in Flask

To enable CORS in Flask, you can use the Flask-CORS extension. First, you need to install the extension by running the following command:

      pip install flask-cors
    

Once you have installed Flask-CORS, you can use it in your Flask application as follows:

      
        from flask import Flask
        from flask_cors import CORS
        
        app = Flask(__name__)
        CORS(app)
      
    

This code snippet initializes the Flask-CORS extension in your Flask application, allowing cross-origin requests to be made.

Configuring CORS Options

You can also configure CORS options in Flask-CORS to specify which origins are allowed, which methods are allowed, and other settings. For example, you can define the allowed origins as a list of domains:

      
        from flask import Flask
        from flask_cors import CORS
        
        app = Flask(__name__)
        CORS(app, origins=['http://example.com', 'https://example.com'])
      
    

This code snippet restricts cross-origin requests to only the specified domains.

Conclusion

Enabling CORS in your Flask application allows you to make cross-origin requests securely. By using the Flask-CORS extension, you can easily configure CORS options and control which origins are allowed to access your resources.

For more information on Flask-CORS, you can refer to the official documentation here.