javascript - 显示从 POST 请求收到的返回
问题描述
我正在使用香草 javascript 创建POST
对我的 Flask 应用程序的请求。当用户尝试使用现有用户名注册时,我会进行验证检查。我将 406 状态连同“错误”一起发回:“用户名已被占用”。
我的问题是,如何从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,
}),
});
解决方案
如果您使用 Promise,则首先检查status
响应的属性,如果是 406,则显示错误,如果您使用的是异步等待而不是尝试status
从响应变量中读取属性。
像这样的承诺示例
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
}
});