I’m running simple Flask back end
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
cors = CORS(app)
@app.route("/")
def home():
return {"name": "John", "age": 30}
if __name__ == "__main__":
app.run(debug=True)
and trying to log JSON on front end
function App() {
const [data, setData] = useState([{}])
useEffect(() => {
fetch("http://localhost:5000/").then(
res => res.json()
).then(
data => {
setData(data)
console.log(data)
}
)
}, [])
return (
<div className="App">
</div>
);
}
Also in package.json
I have "proxy": "http://localhost:5000/",
No matter what I always get
JSON.parse: unexpected character at line 1 column 1 of the JSON data
What’s causing the issue and how can I fix this?
UPD:
After adding CORS and http://localhost:5000
to fetch
and package.json
I started to receive another error of
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/. (Reason: CORS request did not succeed). Status code: (null) Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.
UPD2:
The previous error was caused by having https
instead of http
in
useEffect(() => {
fetch("http://localhost:5000/")
3
Answers
Well, if you are running your flask app in a different port, like, for example, if your backend is exposed on
http://localhost:8000/
and you React app is running athttp://localhost:3000/
, then you need to specify the host in yourfetch
request, likeI also suggest you to add
return data;
as a best practice, so you can chain multiple.then()
.It is likely that your are getting the error since the answer you are receiving, from the frontend (
localhost:3000/
, the one you are using by mistake) is somethin like a not found page that begins with<html>
tag, that’s why you are getting theunexpected character
error, since the not found page does not contains JSON, but HTML instead.your fetch url is just "/"? because if you are trying to acces a server localhost, need to set "http://localhost:YourPORT/". Try it to your fetch.
Don’t forget to configure the CORS in your server for access locally.
change your front to :
and check your problem