0
0
FlaskDebug / FixBeginner · 4 min read

How to Fix CORS Error in Flask: Simple Steps

To fix a CORS error in Flask, install and use the Flask-CORS extension to allow cross-origin requests. Add from flask_cors import CORS and initialize it with your app using CORS(app) to enable CORS properly.
🔍

Why This Happens

CORS (Cross-Origin Resource Sharing) errors happen because browsers block web pages from making requests to a different domain than the one that served the page. Flask by default does not allow cross-origin requests, so when your frontend tries to call your Flask backend from another origin, the browser stops it and shows a CORS error.

python
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/data')
def data():
    return jsonify({'message': 'Hello from Flask!'})

if __name__ == '__main__':
    app.run()
Output
Access to fetch at 'http://localhost:5000/data' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
🔧

The Fix

To fix the CORS error, you need to tell Flask to allow requests from other origins. The easiest way is to use the Flask-CORS extension. It adds the necessary headers so browsers allow your frontend to communicate with your backend.

python
from flask import Flask, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # This enables CORS for all routes and origins

@app.route('/data')
def data():
    return jsonify({'message': 'Hello from Flask!'})

if __name__ == '__main__':
    app.run()
Output
The frontend can now successfully fetch data from the Flask backend without CORS errors.
🛡️

Prevention

To avoid CORS errors in the future, always configure your backend to allow cross-origin requests if your frontend and backend run on different domains or ports. Use Flask-CORS with specific origins allowed instead of all origins for better security. Regularly test your API with your frontend during development to catch CORS issues early.

python
from flask_cors import CORS

# Allow only specific origins
CORS(app, resources={r"/*": {"origins": ["http://localhost:3000"]}})
⚠️

Related Errors

Other errors similar to CORS include:

  • Preflight request failures: Happens when the browser sends an OPTIONS request before the actual request and the server does not respond correctly.
  • Missing headers: If the server does not send Access-Control-Allow-Origin header, the browser blocks the request.
  • Credential issues: When sending cookies or authorization headers, you must configure CORS to allow credentials explicitly.

Key Takeaways

Use Flask-CORS extension to enable cross-origin requests in Flask apps.
Configure CORS to allow only trusted origins for better security.
Test frontend-backend communication early to catch CORS issues.
Understand that CORS errors are browser security features, not backend bugs.
Handle preflight OPTIONS requests properly when needed.