I can't get this very basic piece of code to work in the new version. Here is my code
const express = require("express");
const bodyParser = require("body-parser");
const validator = require("express-validator");
const { check, validationResult } = require("express-validator/check");
const app = express();
app.use(bodyParser.json());
app.use(validator());
app.post('/',
[ check("email").isEmail() ],
(req, resp) => {
const errors = validationResult(req);
resp.send(errors.mapped()); });
app.listen(3000, () => { console.log('listening on port 3000'); });
I send a post request with body containing :
{ "email": "ha@gmail.com" }
The Response is ALWAYS an error even if the email I give is perfectly correct
{ "email": { "location": "body", "param": "email", "msg": "Invalid value" } }
Am i missing something ?
That's because req.body.email
is always undefined
, you have to tell body-parser
middleware to parse incoming request bodies into object by adding this line:
app.use(bodyParser.urlencoded({ extended: true }));
One other thing, always use errors.isEmpty()
to check whether the validation contains errors or not:
app.post('/send', [ check("email").isEmail() ], (req, resp) => {
console.log(req.body);
const errors = validationResult(req);
if (!errors.isEmpty()) {
return resp.send(errors.mapped());
}
resp.send('no errors');
});