DEV Community

Cover image for Fast way to enable CORS in Flask servers
Matheus Guimarães
Matheus Guimarães

Posted on

Fast way to enable CORS in Flask servers

Originally published at https://matheustguimaraes.com/blog/flask-cors

Fast way to enable CORS in Flask servers

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own. [1]

Lets create a simple Flask server called app.py:

from flask import Flask, jsonify


@app.route("/", methods=["GET"])
def get_example():
    """GET in server"""
    response = jsonify(message="Simple server is running")
    return response

@app.route("/", methods=["POST"])
def post_example():
    """POST in server"""
    return jsonify(message="POST request returned")

if __name__ == "__main__":
    app.run(host="0.0.0.0", port="5000", debug=True)

If you are building an React app and using axios library, GET requests to server will look something like this:

import axios from "axios"

const apiURL = "http://localhost:5000"

axios
    .get(apiURL)
        .then((response) => {
            setState(response.message);
        })
    .catch((error) => {
        console.log(error);
    });

But without CORS enabled, the browser will block the server's response for security reasons. To receive data using a React application, CORS must be enabled.

To enable CORS in GET responses on the server, you can simply add a header in response:

@app.route("/", methods=["GET"])
def get_example():
    """GET in server"""
    response = jsonify(message="Simple server is running")

    # Enable Access-Control-Allow-Origin
    response.headers.add("Access-Control-Allow-Origin", "*")
    return response

After

response.headers.add("Access-Control-Allow-Origin", "*")

, all GET requests will be accepted.

To enable requests like POST, PUT, DELETE, etc., the easiest way is to install Flask-CORS (https://flask-cors.readthedocs.io/en/latest). To install Flask-CORS using pip:

pip install flask-cors

In an example of a POST request, simply add the decorator @cross_origin in the function beginning:

@app.route("/", methods=["POST"])
@cross_origin()
def post_example():
    """POST in server"""
    return jsonify(message="POST request returned")

There you go. Now your React app can communicate, receive and send information to the server using all HTTP methods, including POST, PUT, DELETE and more.

Have a nice day!

Follow me on https://twitter.com/matheusguimr to talk more about web development :)

Top comments (9)

Collapse
 
mburszley profile image
Maximilian Burszley

If your intent is only for your frontend to communicate with your backend, you should be more strict about your CORS ACL, but then this whole article can be boiled down to reading the flask-cors documentation.

Collapse
 
lucaszapico profile image
LucasZapico

Love it when our community passes off near docs copy / paste for articles. 😖

Collapse
 
wasosky11 profile image
Wasosky

File "/home/pelu/Projects/PythonFlask/src/app.py", line 103, in
@cross_origin()
NameError: name 'cross_origin' is not defined

Collapse
 
rajojon23 profile image
rajojon23

I had the same issue. I ended up using the code from the flask cors documentation:

from flask import Flask
from flask_cors import CORS

app = Flask(name)
CORS(app)

@app.route("/")
def helloWorld():
return "Hello, cross-origin-world!"

Collapse
 
hidialgo profile image
Hashan Mahesh

you need to import it first

"from flask_cors import cross_origin"

Collapse
 
sahil13399 profile image
sahil-13399

I'm getting this same error, did you find any solution?

Collapse
 
wasosky11 profile image
Wasosky

No yet, if you found any solution please contact me, wasosky313@gmail.com

Collapse
 
dlite profile image
Dlite

from flask import cross_origin

@cross_origin()
@app.route('/')
def index ();
return 'Cors enabled'

Collapse
 
aslasn profile image
Ande

yes