Reputation: 3301
I want to use express-validator in my app.
Here is my app.js code:
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.methodOverride());
app.use(app.router);
app.use(express.bodyParser());
app.use(express.urlencoded());
app.use(express.json());
app.use(expressValidator());
Below is my route:
module.exports = function(app) {
app.post('/login', userController.login);
}
And here is my code for login:
exports.login = function(req, res, next) {
req.assert('email', 'Email not valid').isEmail();
var errors = req.validationErrors();
if (errors) {
return res.redirect('/login');
}
passport.authenticate('local', function(err, user, info) {
// do stuff
})(req, res, next);
};
When I try to post something to /login I got the follwoing error message :
TypeError: Object # <IncomingMessage> has no method 'assert'
I saw that this might be related to an issue with app.use but right now i'm stuck...
EDIT 1 : I change my app.use to those ones, but it doesn't solve my issue:
app.use(express.logger('dev'));
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(express.urlencoded());
app.use(express.json());
app.use(expressValidator());
app.use(app.router);
Upvotes: 2
Views: 9163
Reputation: 663
Kindly check by replacing assert with checkBody.
req.checkBody('email', 'Email not valid').notEmpty().
Do it like this.
Upvotes: 0
Reputation: 845
I had the same issue! your app.js and route.js code are just fine, but in your code for login, you have to change from:
req.assert('email', 'Email not valid').notEmpty();
and replace it for:
req.check('email', 'Email not valid').notEmpty();
If you see the code https://github.com/ctavan/express-validator/blob/master/lib/express_validator.js on line 198, assert is only an alias for check. And seems to have an issue with that name "assert", maybe confuses nodejs because there is a module called "assert", is only a guess. Anyway, seems to work just fine with it.
Hope it helps!
Upvotes: 0
Reputation: 203554
You should use app.router
only after any middleware that you're going to use in your routes:
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(express.urlencoded());
app.use(express.json());
app.use(expressValidator());
app.use(app.router);
The reason is that the order in which you declare middleware with Express is very important: if you add app.router
before expressValidator
, it means, that the router middleware will get to handle requests before the validator middleware is even called and got a chance to add its magic to req
.
Upvotes: 1