I have seen a number of posts which seem to say body-parser is deprecated at least for using with express-validator. I also can see no mention of body-parser on the express-validation documentation Getting Started page. However, when I try and follow that Getting Started tutorial I find I can not get it to work without body-parser. I could not follow their tutorial precisely because I did not understand some of it but I do not think the simplifications I have made would be relevant to this issue.
My question is: is it OK to use body-parser in the way I am doing it?
Below is what I did (I have node version 10.10.0):
mkdir express-validator
cd express-validator
npm install --save express
npm install --save express-validator
app.js file:
const express = require('express')
const app = express()
app.use(express.json())
const { check, validationResult } = require('express-validator/check')
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.post('/user', [
// username must be an email
check('username').isEmail(),
// password must be at least 5 chars long
check('password').isLength({ min: 5})
], (req, res) => {
// Finds the validation errors in this request and wraps them in an object with handy functions
const errors = validationResult(req)
if (!errors.isEmpty()) {
res.send(errors.array())
return
}
res.send('ok')
})
app.listen(5000, () => console.log(`listening on port $5000`))
I start the server using node app.js
Then I use curl:
curl -d username=fred@gmail.com -d password=12345 localhost:5000/user
That works ie I get OK sent back. If I remove the @ symbol from the email address I get this:
[{"location":"body","param":"username","value":"fredgmail.com","msg":"Invalid value"}]
If I comment out the line: app.use(bodyParer.url etc etc
I get the error.array() sent back with both the curl commands above.
Is it OK to use body-parser as I have done? If not what should I do to get this to work?
Yes, that's correct usage.
There's no mention of bodyParser
in the express-validator docs because most of the time you don't need it.
JSON and urlencoded body parsing are included within express nowadays, so you don't need another package if you are only dealing with them; you just have to make sure your app uses express.json()
or express.urlencoded()
:
app.use(express.urlencoded());
// is the same as
app.use(bodyParser.urlencoded());