Lanti Lanti - 6 months ago 22
Node.js Question

Express: Why cannot use req.body.value in router.use?

I try to expose my form validation script both to

router.post
and
router.get
in a
router.use
. I getting the data from the input fields with
req.body.value
. This is works in
router.post
, but not in
router.use
. I get the following error message (
TypeError: Cannot read property 'length' of undefined
) for this code:

router.use('/', (req, res, next) => {
if(req.body.firstname.length === 0 || !req.body.firstname.match(/\D+/igm)) {
var validateFirstname = false;
} else {
var validateFirstname = true;
};

if(validateFirstname === true) {
console.log('SUCCESS: Form validated!');
} else {
console.log('ERROR: Form not validated!');
};
next();
});


Someone can explain to me why is that? There's no way to implement this
if else
statement into
router.use
? Later on this will be a huge help to send html div back to the user when the form validated inside
router.get
.

Answer

As body parsing doesn't make sense for GET requests, body-parser does not work for general router.use which is intended for all request methods.

As good alternative how can you organize validation I suggest to use express-validator module.

Sample

var util = require('util'),
    express = require('express'),
    expressValidator = require('express-validator'),
    app = express.createServer();

app.use(express.bodyParser());

// this line must be immediately after express.bodyParser()! 
app.use(expressValidator([options])); 

app.post('/:urlparam', function(req, res) {     
  // VALIDATION 
  // checkBody only checks req.body; none of the other req parameters 
  // Similarly checkParams only checks in req.params (URL params) and 
  // checkQuery only checks req.query (GET params). 
  req.checkBody('postparam', 'Invalid postparam').notEmpty().isInt();
  req.checkParams('urlparam', 'Invalid urlparam').isAlpha();
  req.checkQuery('getparam', 'Invalid getparam').isInt();
  ...
  var errors = req.validationErrors();
  ...
});
Comments