Lanti Lanti - 1 year ago 75
Node.js Question

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

I try to expose my form validation script both to
in a
. I getting the data from the input fields with
. This is works in
, but not in
. 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!');

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

Answer Source

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.


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


// this line must be immediately after express.bodyParser()! 
app.use(expressValidator([options]));'/:urlparam', function(req, res) {     
  // 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();