【发布时间】:2019-09-11 01:42:03
【问题描述】:
我正在使用 nodejs 制作一个宁静的 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)
当我尝试
logreq.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
})
})
})
这就是我发送请求的方式
【问题讨论】:
-
你在添加路由器之前使用的是
bodyparser吗?你也可以看看stackoverflow.com/questions/38075763/message-path-is-required -
@eol 是的,我正在使用 body-parser。
-
@eol 我访问了这个链接,但这并不能解决我的问题,因为我也在上传图片,所以我需要使用
form-data -
你确定邮递员的表单数据请求中的标题没有尾随空格吗?为了确定,也许可以导出为 curl。
-
@eol 是的,我确定标题没有尾随空格。