我正在使用nodejs创建一个restful API。在这里我添加了multer文件上传,然后实现multer它工作正常,但现在每当我尝试使用postman
创建帖子时,我得到的错误就像这样。
错误
{ ValidationError: Post validation failed: title: Path `title` is required.
at ValidationError.inspect (C:\projects\adi-site\api\node_modules\mongoose\l
ib\error\validation.js:59:24)
at formatValue (internal/util/inspect.js:490:31)
at inspect (internal/util/inspect.js:191:10)
at Object.formatWithOptions (util.js:84:12)
at Console.(anonymous function) (console.js:188:15)
at Console.log (console.js:199:31)
at post.save.then.catch.err (C:\projects\adi-site\api\src\routes\posts.js:70
:17)
at process._tickCallback (internal/process/next_tick.js:68:7)
errors:
{ title:
{ ValidatorError: Path `title` is required.
at new ValidatorError (C:\projects\adi-site\api\node_modules\mongoose\lib\error\validator.js:29:11)
at validate (C:\projects\adi-site\api\node_modules\mongoose\lib\schematype.js:975:13)
at C:\projects\adi-site\api\node_modules\mongoose\lib\schematype.js:1028:11
at Array.forEach (<anonymous>)
at SchemaString.SchemaType.doValidate (C:\projects\adi-site\api\node_modules\mongoose\lib\schematype.js:984:19)
at C:\projects\adi-site\api\node_modules\mongoose\lib\document.js:2098:9
at process._tickCallback (internal/process/next_tick.js:61:11)
当我尝试
log
req.body我得到这个
[Object: null prototype] {
'title ': 'this is title with imahih', <-----//i think here `key` title is in the wrong format I have no idea where it is coming from and how to fix this.
overview: 'this is overview of the image',
content: 'this is image content' }
routes / posts.js < - 这是我的代码
router.post('/', upload.single('postImage'),(req, res, next) => {
console.log(req.body);
const post = new Post({
_id: new mongoose.Types.ObjectId(),
title: req.body.title,
overview: req.body.overview,
content: req.body.content,
postImage: req.file.path
});
post.save().then(result => {
console.log(result);
res.status(201).json({
message: "Post created",
createdPost: {
_id: result._id,
title: result.title,
overview: result.overview,
content: result.content,
postImage: result.postImage
}
})
}).catch(err => {
console.log(err);
res.status(500).json({
error: err
})
})
})
这就是我发送请求的方式
后验证失败:标题:路径
title
是必需的。
你收到这个错误是因为在postman形式的title
之后有一个空格。
[Object: null prototype] {
'title ': 'this is title with imahih', // You can notice title being wrapped in '' with extra space
overview: 'this is overview of the image',
content: 'this is image content' }
您可以修剪邮递员的额外空间或在服务器端处理案例。
'use strict';
router.post('/', upload.single('postImage'), (req, res, next) => {
console.log(req.body);
const formData = Object.keys(req.body).reduce((cleanFormData, attribute) => {
const key = attribute.trim();
cleanFormData [key] = req.body[attribute];
return cleanFormData;
}, {});
console.log(formData);
console.log(formData.title); // logs 'this is title with imahih'
.....
});