Home > Software engineering >  express-validator can't evaluate body fields when form-data is used
express-validator can't evaluate body fields when form-data is used

Time:03-25

I am trying to use express-validator in combination with multer to validate the body components of a POST request that also contains an image, headers, and params. I have tried using the body() style validation methods and also the checkSchema style but neither will correctly validate my body text fields. The checkSchema style will work on my headers and params but not the body for some reason. Maybe I need to rearrange things somewhat?

const express = require('express');
const multer = require('multer');
const { checkSchema } = require('express-validator');
const router = express.Router();
const upload = multer();

// inputs coming in from everywhere - header, params and form-data
router.post(
  '/:aId/help/:tId/blah',
  checkSchema({
    aId: {
      // The location of the field, can be one or more of body, cookies, headers, params or query.
      // this check works!
      in: ['params'],
      errorMessage: 'aId is wrong',
      isAscii: true
    },
    tId: {
    // this check works
      in: ['headers'],
      errorMessage: 'pId is wrong',
      isAscii: true
    },
    uploadedTime: {
    // these checks fail to work
      in: ['body'],
      errorMessage: 'uploadedTime is wrong',
      isInt: true
    },
    uploadedByName: {
      // these checks fail to work
      in: ['body'],
      errorMessage: 'uploadedByName is wrong',
      isInt: false
    }
  }),
  upload.single('file'),
  async (req, res) => {
    console.log('ANY REQ params?', req.params);
    console.log('ANY headers?', req.headers);
    console.log('ANY BODY?', req.body);
    console.log('ANY FILES?', req.file);
  }
);

enter image description here

my log shows this for body:

ANY BODY? [Object: null prototype] {
  uploadedTime: '1646762107739',
  uploadedByName: 'Moe S'
}

CodePudding user response:

the multer usage needs to go before the validation

  • Related