skip to Main Content

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:

  1. Adding headers directly to the response
  2. Wrapping app in CORS(app)
  3. Using the @cross_origin decorator with localhost
  4. app.config[‘CORS_HEADERS’] = ‘Content-Type’
  5. All of the above together

No matter what, the error persists.

2

Answers


  1. Chosen as BEST ANSWER

    So I figured it out. Since I'm using vite with React, there is a different procedure for proxy and calling APIs.

    1. Go to the vite.config file
    2. Paste the following into the export default defineConfig statement:
    server: {
        proxy: {
          '/api': {
               target: 'http://127.0.0.1:5000',
               changeOrigin: true,
               secure: false,
           }
      }
    

    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.


  2. 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().

    app = Flask(__name__)
    CORS(app)
    

    or

    @app.route("/")
    @cross_origin()
    ....
    

    https://flask-cors.readthedocs.io/en/latest/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search