问题描述
我有一个使用 express-validator
来验证请求的中间件,
const { validationResult } = require("express-validator");
module.exports = {
validate: (req,res,next) => {
const raw_errors = validationResult(req);
if (raw_errors.isEmpty()) {
return next()
}
const errors = raw_errors.errors.map((err) => ({ message: err.msg }));
return res.status(422).json({ status: "error",errors });
},}
我像这样在路线上使用它:
const { validate } = require('../middlewares/validation')
routes.post('/',validate,(req,res) => {
postService.add(req.body.name,req.body.description).then(post => {
res.status(201).json({ message: 'post added',data: post })
}).catch(error => {
handleError(error,res)
})
})
但是当我尝试使用空请求正文进行 API 调用时,它不会返回任何错误。
这是我的模型
const mongoose = require('mongoose');
const PostSchema = mongoose.Schema( {
name: {
type: String,required: [true,'Please provide a name'],},description: {
type: String,'Please provide a description'],}
},{timestamps: true}
);
module.exports = mongoose.model('Post',PostSchema);
这是我的postService
module.exports = {
//adds a post
add : async (name,description) => {
try{
const tab = { name,description }
return postModel.create(tab)
}
catch(err){
throw new ErrorHandler(500,"Unable to add post at this time. Please try again later.")
}
},}
当我从中间件登录 raw_errors
时,我得到 - Result { formatter: [Function: formatter],errors: [] }
请问有什么问题?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)