[英]How do I make a post request from react.js front end to flask backend that sends data but also grabs data?
I am posting a user id to the backend route /stat.我将用户 ID 发布到后端路由 /stat。 In /stat I want to perform a query that takes in user id as a parameter.在 /stat 我想执行一个以用户 ID 作为参数的查询。 Then I also want to get the result of the query in the front end so I can display the value.然后我还想在前端获取查询的结果,以便显示该值。 I understand how to make a post request that successfully sends the data, but how do I program it to also grab data?我了解如何发出成功发送数据的发布请求,但是如何对其进行编程以获取数据?
my post request on the front end looks like this:我在前端的 post 请求如下所示:
const postData = (username) => {
try {
let result = fetch('http://127.0.0.1:5000/stat', {
credentials: 'include',
method: 'POST',
mode: 'no-cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
user: username
})
});
} catch(e) {
console.log(e)
}
}
and my backend route /stat looks like this:我的后端路由 /stat 如下所示:
@app.route('/stat', methods=['GET', 'POST'])
def stats():
request_data = request.get_json()
user = request_data['user']
def get_total_percent_correct(user):
correct = d.db_query('SELECT COUNT(*) FROM cards.responses WHERE guess = answer AND user_id = %s' % user)
total = d.db_query('SELECT COUNT(*) FROM cards.responses WHERE user_id = %s' % user)
return float(correct[0][0])/float(total[0][0])
response_body = {
"totalAccuracy": get_total_percent_correct(user),
"user" : user
}
return response_body
You need to get the response from the fetch call.您需要从 fetch 调用中获取响应。 If you send JSON from the backend this is how it would look:如果您从后端发送 JSON 这就是它的样子:
fetch('http://127.0.0.1:5000/stat', {
credentials: 'include',
method: 'POST',
mode: 'no-cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
user: username
})
})
.then(function(response) {
console.log(response.json())
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.