首页 > 解决方案 > 在结果消息猫鼬节点验证中显示实际错误

问题描述

我在 node.js/react 中使用 mongoose 和 axios,需要在客户端获取特定的验证错误,以便我可以更新表单。在这种情况下,用户电子邮件已经是数据库并且不是唯一的。返回到前端的错误似乎没有用。我在前端尝试了 err.message,但它什么也没给我。我如何调用特定的错误消息告诉我实际错误?

调用前端 API 并包括:

  API.createUser({
    userEmail: this.state.profile.email.toLowerCase(),
   })
    .catch(err => console.log(err))

后端控制器

  db.WmUser
      .create(req.body)
      .then(dbModel => res.json(dbModel))
      .catch(err => res.status(422).json(err));

MONGOOSE 模式包括:

userEmail: {type: String, unique: true, required: true},

结果返回前端错误:

Error: Request failed with status code 422
    at createError (createError.js:16)
    at settle (settle.js:18)
    at XMLHttpRequest.handleLoad (xhr.js:77)

结果在控制器后端返回:

如果我在控制器中使用以下代码,我会收到我需要但不知道如何将其带回前端的错误消息:

  .catch(err=> console.log(err.message))

标签: node.jsmongodbreactjsmongooseaxios

解决方案


问题是我在前端调用错误的方式。它必须是 error.response 以防有人遇到这个问题

在前端调用 AXIOS 的函数

  API.createUser({
    userEmail: this.state.profile.email.toLowerCase(),
        })
   .then(function (response) {
    console.log(response);
   })
   .catch(function (error) {
    if(error.response.data.code == 11000){
      console.log("THE EMAIL IS ALREADY IN THE DATABASE");
    }
    console.log(error.response);
   })

API 文件中的 AXIOS 函数

createUser: function(userData){ 
     return axios.post("/api/wmUser/", userData);
    }

推荐阅读