在React中获取猫鼬验证错误消息

时间:2020-10-14 15:15:41

标签: node.js reactjs mongoose axios

我正在尝试使用Mongoose验证用户创建/编辑等操作,并在前端获取消息,但是我得到的只是

POST http://192.168.0.11:3000/users/create 400 (Bad Request)
CreateUser.jsx:48 Error: Request failed with status code 400
    at e.exports (createError.js:16)
    at e.exports (settle.js:17)
    at XMLHttpRequest.d.onreadystatechange (xhr.js:61)

我的用户架构:

const User = new mongoose.Schema({
  Name: {
    type: String,
    required: "Username is required for a user!",
    minlength: 4,
    maxlength: 16,
  },
  Password: {
    type: String,
    required: "Password is required for a user!",
    minlength: 4,
    maxlength: 20,
  },
  Role: {
    type: String,
    required: "User must have a role!",
    enum: ["Operator", "Admin"],
  }
});

在节点中:

router.post("/create", async (req, res) => {
  try {
    const user = new User({
      Name: req.body.Name,
      Password: req.body.Password,
      Robots: req.body.Robots,
      Role: req.body.Role,
    });

    await user.save();
    res.send("success");
  } catch (e) {
    console.log(e);
    res.status(400).json("Error" + e);
  }
});

在React中:

try {  
  const userCreated = await axios.post(`${ENDPOINT}/users/create`, user);
  console.log(userCreated);
} catch (e) {
  console.log(e);
}

如果成功,我将返回“成功”消息,但否则,我将继续收到POST 400错误请求消息。

如果我在节点内进行console.log记录,它的确会抛出验证失败的错误,但是我无法在前端找到错误。

1 个答案:

答案 0 :(得分:0)

我用我的一个快速样板仓库here尝试了几乎相同的示例,并且能够返回这样的Mongo验证错误。

用户模型的一部分

first_name: {
      type: String,
      trim: true,
      minlength: 4,
}

控制器

try {
   const user = await new User(req.body);
   const newUser = await user.save();
   res.status(201).json({ status: true, newUser });

} catch (error) {
   console.log(error);
   res.status(400).json(error);
}

我收到了400错误请求的错误响应,因此您可以检查自己的应用程序name == 'ValidationError'中的catch,也可以使用errors与该字段一起显示。

{
    "errors": {
        "first_name": {
            "message": "Path `first_name` (`a`) is shorter than the minimum allowed length (4).",
            "name": "ValidatorError",
            "properties": {
                "message": "Path `first_name` (`a`) is shorter than the minimum allowed length (4).",
                "type": "minlength",
                "minlength": 4,
                "path": "first_name",
                "value": "a"
            },
            "kind": "minlength",
            "path": "first_name",
            "value": "a"
        }
    },
    "_message": "User validation failed",
    "message": "User validation failed: first_name: Path `first_name` (`a`) is shorter than the minimum allowed length (4).",
    "name": "ValidationError"
}