node.js - 使用 Vue 处理来自 Express API 的错误

标签 node.js json express vue.js axios

我在访问返回 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: '电子邮件已存在!' });

我的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)
      })
}

最佳答案

您必须使用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);
          }
      })
}

See axios 错误处理文档

关于node.js - 使用 Vue 处理来自 Express API 的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55203887/

相关文章:

java - 有效比较2个json

Node.js 和 Express Web API 无法在 Azure 上运行

node.js - Node + 连接 + WebSockets

javascript - Node.js 和 ES6

node.js - 部署到heroku Angular 4

json - Angularjs - $http 发布数据中的等号

javascript - 如何比较对象内的值具有不同序列的数组javascript

node.js - 由于 Mongoose.model,开 Jest 没有关闭

node.js - 我的请求正文在 Node API 中显示为空或未定义

node.js - Express 和 Socket.IO 共享 cookie