【问题标题】:How to get a backend error message on the frontend using Fetch如何使用 Fetch 在前端获取后端错误消息
【发布时间】:2019-03-04 02:34:02
【问题描述】:

我不明白fetch 如何将错误消息从后端返回到前端。我不确定要在前端的fetch 函数的错误代码中添加什么样的属性。目标是发送错误(“电子邮件地址是..”)并将其显示在 UI 中。

后端发布请求详细信息。如果用户已经注册,则抛出 400 错误。

const signupPost = function (req, res) {
  Base.findOne({
    userName: req.body.userName
  }, 
  function (user, err) {
    if (err) {
      return res.status(400).send({
        error: 'The email address you have entered is already associated with another account.'
      });
    }

这是我的 Vue 前端的错误处理方法:

methods: {
  signup() {
    this.errorMessage = '';

    if (this.validUser()) {
      const body = {
        userName: this.user.userName,
        firstName: this.user.firstName,
        lastName: this.user.lastName,
        telephone: this.user.telephone,
        password: this.user.password
      }

      fetch(SIGNUP_URL, {
        method: 'POST',
        body: JSON.stringify(body),
        headers: {
          'content-type': 'application/json'
        }
      })
      .then((response) => {
        if (response.ok) {
          return response.json();
        }
        return response.json().then((error) => {
          throw new Error(error);
        })
      })
      .then(user => {
        console.log(user)
      })
      .catch((error) => {
        this.errorMessage = error
      });
    }
  },

【问题讨论】:

    标签: node.js express vue.js fetch


    【解决方案1】:

    你快到了。 您应该在返回的正文中访问error

    return response.json().then((body) => {
      throw new Error(body.error)
    })
    

    然后在返回的error 对象上使用message

    .catch((error) => {
      this.errorMessage = error.message
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-21
      • 2021-07-29
      • 1970-01-01
      • 2018-05-23
      • 2022-01-21
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      相关资源
      最近更新 更多