[英]Sending JSON response in Flask “POST” Route
For reference, I've looked at these three questions:作为参考,我查看了以下三个问题:
Return JSON response from Flask view 从 Flask 视图返回 JSON 响应
Sending JSON and status code with a Flask response 使用 Flask 响应发送 JSON 和状态代码
Return a requests.Response object from Flask 从 Flask 返回一个 requests.Response object
As the title states, I am trying to return a JSON response from a flask post method.正如标题所述,我试图从 flask 发布方法返回 JSON 响应。 The flask route is as follows: flask路线如下:
@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).在我的 web 应用程序中,我想将会话session-token
存储在 cookies 中(现在)。
Currently on the web side I have the following code:目前在 web 方面我有以下代码:
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.其中userObject
由username
和password
属性组成。 I've tried a few variations of my flask route given the previous searches listed above:鉴于上面列出的先前搜索,我已经尝试了 flask 路线的一些变体:
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 :最后, 建议尝试创建一个新的响应 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:所有这 3 次尝试都将以下 json 响应对象返回到我的 chrome 控制台:
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
.如您所见,响应 object 不包含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.我真的不确定这里可能出了什么问题,我也不确定问题是否出在 flask 路由或 javascript 上。 Needless to say I could use some help and any recommendations would be appreciated.不用说,我可以使用一些帮助,任何建议都将不胜感激。 I am using Flask version 1.1.2.我正在使用 Flask 版本 1.1.2。
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. Javascript 中的fetch
API 很好,因为它为您提供了当您记录它时看到的选项,就像可能访问身体一样 stream (现在任何一天都超过了 9 天)... % 案子。 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.如果您是像我这样的老顽固的老顽固,现在抱怨孩子们的桌子和午餐时间很酷,请使用另一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.