In my React app, I’m making a call to a Flask API but it’s being blocked by CORS, which is giving the following error: Access to XMLHttpRequest at ‘http://localhost:5000/’ from origin ‘http://localhost:5173’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
React:
import { useEffect, useState } from "react";
import axios from "axios";
import "./App.css";
function App() {
useEffect(() => {
// Define the API URL
const apiUrl = "http://localhost:5000/";
// Make the Axios GET request
axios
.get(apiUrl)
.then((response) => {
// Handle the response data
console.log(response);
})
.catch((error) => {
// Handle any errors
console.error("Error fetching data:", error);
});
}, []);
return <div>Hello</div>;
}
export default App;
Flask:
from flask import Flask
from flask_cors import CORS
from flask import jsonify
app = Flask(__name__)
@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
if __name__ == '__main__':
app.run()
Things I’ve tried:
- Adding headers directly to the response
- Wrapping app in CORS(app)
- Using the @cross_origin decorator with localhost
- app.config[‘CORS_HEADERS’] = ‘Content-Type’
- All of the above together
No matter what, the error persists.
2
Answers
So I figured it out. Since I'm using vite with React, there is a different procedure for proxy and calling APIs.
Make sure the target is your desired target and port. Also do not use "localhost"; use the IPv4 address instead.
When calling the API, you have to use "/api" before your actual route. For example, if my end point was localhost:5000/hello, I would put "/api/hello" in my api call (using fetch, axios, etc.). Also, make sure your API endpoint has the /api before the actual route as well. If my route looks like this: @app.route("/hello"), make it @app.route("/api/hello") and it should work.
You have to wrap the "app" with CORS as the flask_cors module documentation suggest, or if need to use for specific route, then add a simple decorator @cross_origin().
or
https://flask-cors.readthedocs.io/en/latest/