troubleshooting Question

CORS issues for Flask API call from React both in localhost

Avatar of ltpitt
ltpitt asked on
JavaScriptJSON
1 Comment1 Solution94 ViewsLast Modified:
I am calling a Flask API from React (both running on localhost) and I am running into CORS problems. When the request is made, the browser (Chrome) gives the following error

Access to XMLHttpRequest at 'http://localhost:5000/sas' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

Setup

The Flask setup is the following

from flask_cors import CORS
from flask import Flask, request, Response
from flask_restful import Api, Resource
import json

class SAS(Resource):
    def get(self):
        content = request.json
        js = json.dumps(
            {
                "Response": "Some response"
            }
        )
        resp = Response(js, status=200, mimetype='application/json')
        return resp

app = Flask(__name__)
cors = CORS(app)
api = Api(app)
api.add_resource(SAS, '/sas/')

The call using axios in React is the following

  buttonPressed = async event => {
    event.preventDefault();
    const response = await axios.get(`http://localhost:5000/sas`, {
      data: {
        user: "user",
        file_name: "user",
        directory_name: "user"
      }
    });
  };

NOTE: Running the request from Postman works and shows the header Access-Control-Allow-Origin = *

Any idea on how to solve the problem?

Also, if I was to run the React frontend and API as a dockerized application, I should not see this problem anymore correct?

In this case I would also consider circumnavigating the problem while I am developing
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 1 Comment.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 1 Comment.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros