Reputation: 9417
I have setup a flask
rest API as so:
from flask import Flask
from flask import jsonify
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app)
@app.route('/', methods=['GET'])
def hello_world():
return "Hello World"
if __name__ == '__main__':
app.run()
Now, I have also setup a react front-end. All I want to do is make a GET
request to my flask
rest API and console.log
the resulting string Hello World". I had some
CORSissues so I added the line
CORS(app)`, however I am still having some trouble.
My fetch request looks as so...
componentDidMount() {
fetch('http://localhost:5000/', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(result=>result)
.then(item=>console.log(item))
.catch(e=>{
console.log(e);
return e;
})
}
The result I get back is the following...
Response { type: "cors", url: "http://localhost:5000/", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, bodyUsed: false } App.js:24
There is no sign of my Hello World
string. I also noticed that my server is making an OPTIONS
request...
127.0.0.1 - - [26/Jul/2018 14:13:54] "OPTIONS / HTTP/1.1" 200 -
127.0.0.1 - - [26/Jul/2018 14:13:54] "GET / HTTP/1.1" 200 -
I decided that this might be do to my application/json
in the headers. So I removed it...
fetch('http://localhost:5000/', {
method: 'GET',
})
.then(result=>result)
.then(item=>console.log(item))
.catch(e=>{
console.log(e);
return e;
})
The OPTIONS
request disappeared, however my response is still the same.
I cannot seem to get the string to my front-end. I have no idea what my issue might be anymore.
Upvotes: 3
Views: 2402
Reputation: 6543
Instead of returning a string from your Flask route, you can use jsonify
to return a Response object:
return jsonify({"data": "Hello World"})
Then in React, you can call the json
method on your response to get a JavaScript object containing your data:
.then(result=>result.json()) // instead of .then(result=>result)
You should then see the following logged to the console:
{data: "Hello World"}
Upvotes: 2