'Can't get React and Flask-CORS to work locally
I'm trying to get an application with a React/NodeJS frontend and a Flask backend to run locally for development purposes. I've been scouring StackOverflow for the last hour, but I can't seem to get past the CORS-issue. I have:
import json
from flask import Flask, request
from flask_cors import CORS, cross_origin
app = Flask(__name__)
# Enable cors requests
CORS(app)
# Initiate model
@app.route("/query", methods=["POST"])
@cross_origin(origin="*", headers=["Content-Type"])
def query():
"""Endpoint for receiving bot response"""
print(request)
query = request.json
bot_answer = blablagetanswer() ... #filling the json
return json.dumps({"botResponse": bot_answer})
if __name__ == "__main__":
app.run(
host="0.0.0.0", port=80, debug=True,
)
I have read multiple answers, and tried many variations of CORS handling in Flask (tried with and without the @cross_origin() decorater, added @cross_origin(origin="*") or even @cross_origin(origin="*", headers=["Content-Type"]) right under the @app.route()), but to no avail.
I even tried adding these two lines to my flask app:
app.config["CORS_HEADERS"] = "Content-Type"
CORS(app, resources={r"/*": {"origins": "*"}})
It also didn't help.
I'm fetching from React like this:
var jsonData = { "lastConversations": [this.state.chatInput] }
console.log("Sending Chat: " + JSON.stringify(jsonData, null, 2));
fetch('http://my-ip:80/query', {
method: 'POST',
mode: 'cors',
body: JSON.stringify(jsonData)
})
and the log does contain the text I want to send, but Chrome just says:
Access to fetch at 'http://my-ip/query' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
What am I missing? This is just for local testing, how can I get it to work?
Solution 1:[1]
Turns out when working with JSON, it's important to make sure you let the other side know that you're sending application/json data. Modifying the fetch like this solved it:
var jsonData = { "lastConversations": [this.state.chatInput] }
console.log("Sending Chat: " + JSON.stringify(jsonData, null, 2));
fetch('http://my-ip:80/query', {
method: 'POST',
mode: 'cors',
headers: { # this is the key part
'Content-Type': 'application/json'
},
body: JSON.stringify(jsonData)
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | lte__ |
