node.js - 在 React 中获取 Mongoose 验证错误消息
问题描述
我正在尝试使用 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);
}
});
在反应中:
try {
const userCreated = await axios.post(`${ENDPOINT}/users/create`, user);
console.log(userCreated);
} catch (e) {
console.log(e);
}
如果成功,我会返回“成功”消息,否则我会不断收到 POST 400 错误请求消息。
如果我在节点中 console.log 它确实会引发验证失败错误,但我无法在前端恢复错误。
解决方案
我在这里使用我的一个快速样板回购尝试了几乎相同的示例,并且我能够像这样返回 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 Bad Request 的错误响应,因此您可以检查您的反应应用程序是否已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"
}
推荐阅读
- orleans - 是否可以在经典的 ASP.NET MVC 4 中运行 Microsoft Orleans
- sql - SQL 通过在另一个表列上查找来替换列
- node.js - 模块构建失败(来自 ./node_modules/mini-css-extract-plugin/dist/loader.js)
- javascript - 防止在 JQuery/Javascript 中离开页面时多次点击链接
- reactjs - 如何防止反应材质 UI 文本框上的 XSS?
- php - 在页面上显示 Woocommerce 中 50 英镑到 100 英镑之间的所有产品
- c - 为什么一个 int 变量的值是 `0xffffffff` >> 1 != 0x7fffffff?
- c++ - 我如何在 C++ 中声明一个类
- javascript - DOM JS - 对象 HTMLUnknownElement
- python - Python 通过 cursor.execute 和 mysql 损坏导入的 csv 文件