How to Fix CORS Error in Flask: Simple Steps
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.
from flask import Flask, jsonify app = Flask(__name__) @app.route('/data') def data(): return jsonify({'message': 'Hello from Flask!'}) if __name__ == '__main__': app.run()
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.
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()
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.
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-Originheader, the browser blocks the request. - Credential issues: When sending cookies or authorization headers, you must configure CORS to allow credentials explicitly.