[英]how to make http request at same origin from where front-end is serve to access a directory's file's JSON data in react.js
[英]How do I make a post request from react.js front end to flask backend that sends data but also grabs data?
我將用戶 ID 發布到后端路由 /stat。 在 /stat 我想執行一個以用戶 ID 作為參數的查詢。 然后我還想在前端獲取查詢的結果,以便顯示該值。 我了解如何發出成功發送數據的發布請求,但是如何對其進行編程以獲取數據?
我在前端的 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)
}
}
我的后端路由 /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
您需要從 fetch 調用中獲取響應。 如果您從后端發送 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.