node.js - 在结果消息猫鼬节点验证中显示实际错误
问题描述
我在 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))
解决方案
问题是我在前端调用错误的方式。它必须是 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);
}
推荐阅读
- angular - 检测慢速网络 Angular 9
- javascript - 我无法让特定的“按钮”打开特定的 youtube“iframe”
- git - 共享 github 共同开发(只有 2 个用户)会产生无法解决的推/拉冲突
- twilio - 将呼叫者重定向到代理号码
- python-3.x - 关于KNN参数K值
- excel - Excel:使用 IF、ISNUMBER、SEARCH 进行文本挖掘
- python - 在 Python 中的同一对象上运行两个与计时器相关的函数的问题
- html - 如何使表单提交在移动设备上工作?
- bixby - 在播放音频时添加额外的视图或布局
- python - 递归语句的问题