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.
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
Please try using the cross_origin decorator like in this minimal example:
from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app, support_credentials=True)
@app.route('/sas', methods=['POST', 'GET', 'OPTIONS'])
@cross_origin(supports_credentials=True)
def index():
if(request.method=='POST'):
some_json = request.get_json()
return jsonify({"key": some_json})
else:
return jsonify({"GET": "Nice Get Request"})
if __name__=="__main__":
app.run(host='0.0.0.0', port=5000)
If this works then we'll move to implement the same decorator in your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With