【问题标题】:Handling errors from Express API with Vue使用 Vue 处理来自 Express API 的错误
【发布时间】:2019-08-07 18:57:12
【问题描述】:

我在访问返回 400 错误的 JSON 对象时遇到了一些困难。

我的 Vue 应用程序的响应只有错误 400,没有 JSON 数据。

Error: Request failed with status code 400
    at createError (createError.js?16d0:16)
    at settle (settle.js?db52:18)
    at XMLHttpRequest.handleLoad (xhr.js?ec6c:77)

使用 Postman 的响应会返回错误代码和消息。

如何在我的 Vue 应用中访问 JSON 响应?

{
    "error": "Email already exists!"
}

Express API 代码:

res.status(400).json({ error: 'Email already exists!' });

我的 Vue 代码:

handleSubmit () {
  this.$http.post('http://localhost:3000/users/create', this.user)
      .then(response => {
          const status = JSON.parse(response.status)
          if (status === 200) router.push('/users')
      })
      // why doesn't the json response show
      .catch(err => {
          console.log(err)
      })
}

【问题讨论】:

    标签: node.js json express vue.js axios


    【解决方案1】:

    尝试发送而不是 json?也可能是访问错误。

    BACKEND
    res.status(400).send({ error: 'Email already exists!' })
    
    FRONTEND
    (err) => { console.log(err["error"]) }
    

    【讨论】:

    • 嗯...很难说。这就是我们在我们正在构建的 PWA 上设置它的方式。
    • 继续阅读有关此内容的更多信息,它看起来可能与 Axios 有关。
    • 啊,我明白了,我正在使用 fetch 为我的。 Axios 可能有不同的要求。
    【解决方案2】:

    您必须使用response 属性或error 对象:

    handleSubmit () {
      this.$http.post('http://localhost:3000/users/create', this.user)
          .then(response => {
              // if on server side you use only status 200, here it's always true
              if (response.status=== 200) {
                router.push('/users');
              }
          })
          .catch(error => {
              // error.response can be null
              if (error.response && error.response.status === 400) {
                  console.log(error.response.data.error);
              }
          })
    }
    

    Seeaxios 错误处理文档

    【讨论】:

    • 谢谢,这成功了。我的问题是:console.log(error) 返回的错误信息如下所示,console.log(error.response) 在哪里显示了一个可用的对象。 Error: Request failed with status code 400 at createError (createError.js?16d0:16) at settle (settle.js?db52:18) at XMLHttpRequest.handleLoad (xhr.js?ec6c:77)
    猜你喜欢
    • 2021-08-05
    • 2020-12-20
    • 2018-02-11
    • 2017-07-05
    • 2020-05-13
    • 2020-08-05
    • 2021-08-07
    • 2010-11-11
    • 2017-05-16
    相关资源
    最近更新 更多