Reputation: 1456
For reference, I've looked at these three questions:
Return JSON response from Flask view
Sending JSON and status code with a Flask response
Return a requests.Response object from Flask
As the title states, I am trying to return a JSON response from a flask post method. The flask route is as follows:
@app.route('/login', methods=['POST'])
def login_route():
content = request.json
jwt = get_authorization(content['username'], content['password'])
return {'session-token': jwt} , 200
Where in my web application I would like to store the session-token
in cookies (for now).
Currently on the web side I have the following code:
static postWithJSONResponse(url, body, onFetchComplete, onFetchFailure) {
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
})
.then((data) => onFetchComplete(data))
.catch(error => onFetchFailure(error));
}
componentDidMount() {
NetworkUtils.postWithJSONResponse('/login', this.state.userObject,
(data) => {
console.log(data);
},
(error) => {
});
}
Where userObject
consists of username
and password
attributes.
I've tried a few variations of my flask route given the previous searches listed above:
Variations based on this question
from flask import jsonify
@app.route('/login', post)
def login_route():
content = request.json
d = {}
d['session-token'] = get_authorization(content['username'], content['password'])
return jsonify(d)
This variation from the same post:
@app.route('/login', post)
def login_route():
content = request.json
jwt = get_authorization(content['username'], content['password'])
app.response_class(
response=json.dumps({'session-token': jwt}),
status=200,
mimetype='application/json'
)
And lastly this attempt in which it was recommended to try creating a new response object:
from flask import Flask, request, make_response
@app.route('/login', methods=['POST'])
def login_route():
content = request.json
jwt = get_authorization(content['username'], content['password'])
resp = make_response(json.dumps({'session-token': jwt}), 200)
resp.headers['Content-Type'] = 'application/json'
return resp
All 3 of these attempts return the following json response objects to my chrome console:
Response {type: "basic", url: "http://localhost:3000/login", redirected: false, status: 200, ok: true, …}
body: ReadableStream
locked: false
__proto__: ReadableStream
bodyUsed: false
headers: Headers
__proto__: Headers
ok: true
redirected: false
status: 200
statusText: "OK"
type: "basic"
url: "http://localhost:3000/login"
__proto__: Response
As you can see, the response object doesn't contain a single entry for session-token
. I'm really not sure what could be going wrong here and I'm not certain if the issue is with the flask route or the javascript anymore. Needless to say I could use some help and any recommendations would be appreciated. I am using Flask version 1.1.2.
Upvotes: 1
Views: 2969
Reputation: 21926
The fetch
API in Javascript is nice in the sense that it gives you options you're seeing when you log it like potentially accessing the body as stream (any day now TC 39...), but it's totally over-engineered for the 90% case. The magic incantation to remember is as follows:
// can only do this inside an async function
const resp = await fetch(someURL);
const jsonData = await resp.json();
// step 3, profit
fetch(someURL)
.then(resp => resp.json())
.then(jsonData => /* profit! */);
They are functionally equivalent. Use the newer one if you always wanted to sit at the cool kid's table at lunchtime in school. Use the other if you're a stodgy old curmudgeon like myself who complains about the kids these days with their cool tables and lunchtimes.
Upvotes: 2