[英]Display the return received from a POST request
I'm using vanilla javascript to create a POST
request to my Flask App.我正在使用香草 javascript 创建对我的 Flask 应用程序的POST
请求。 I have a validation check when a user tries to sign up with an existing username.当用户尝试使用现有用户名注册时,我会进行验证检查。 I send a 406 status back along with "Error": "Username already taken."我将 406 状态连同“错误”一起发回:“用户名已被占用”。
My question is, how do I get that error message to display on my frontend from a POST
request?我的问题是,如何从POST
请求中获取该错误消息以显示在我的前端?
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({
username: e.target.username.value,
friend_code: parseInt(e.target.friend_code.value),
dark_mode: null,
theme: null,
avatar: null,
created_at: null,
}),
});
If you're using Promise then in the first then block check the status
property of response and if it's 406 then display error if you're using async await than try to read status
property from your response variable.如果您使用的是 Promise 那么在第一个然后阻止检查响应的status
属性,如果它是 406 则显示错误,如果您使用的是异步等待而不是尝试从响应变量中读取status
属性。
something like this promise example像这样的 promise 示例
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({
username: e.target.username.value,
friend_code: parseInt(e.target.friend_code.value),
dark_mode: null,
theme: null,
avatar: null,
created_at: null,
}),
})
.then(response => {
if (response.status === 406) {
// your display logic
} else {
// other logic
}
});
I have created a similar response -> http://www.mocky.io/v2/5e90c0443300009200e9cc52我创建了一个类似的响应-> http://www.mocky.io/v2/5e90c0443300009200e9cc52
{
"message":"Username already taken"
}
and sent it with 406 status.并以 406 状态发送。
In order to get the message, i did res=> res.json()
to return another promise and then res.message
to get the message为了得到消息,我做了res=> res.json()
返回另一个 promise 然后res.message
得到消息
fetch("http://www.mocky.io/v2/5e90c0443300009200e9cc52")
.then(res=> res.json())
.then(res=> console.log(res.message))
.catch(err=> console.log(err))
In your case res.Error
在你的情况下res.Error
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.