ValidationError:验证后失败:title:需要路径`title`。在nodejs api中

时间:2019-04-21 16:38:00

标签: node.js multer

我正在使用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)
  

当我尝试log必填项时,我得到了

[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
        })
    })
})
  

这是我发送请求的方式

error-image

1 个答案:

答案 0 :(得分:0)

  

验证后失败:标题:路径title是必需的。

您会收到此错误,因为邮递员形式的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'
  .....
});