首页 > 解决方案 > 显示从 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,
  }),
});

标签: javascript

解决方案


如果您使用 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
 }
});

推荐阅读