I have a problem with bodyparser that I can't figure out.
A few weeks ago I created a REST API with Express and used bodyParser to read JSON data from the client. Everything worked well but this morning I tried to launch my application and all my req.body.data are undefined, in fact the body is equal to {}.
Here is my configuration :
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
And then I configure my routes. I've seen that you must declare that in this order, ie bodyParser before your route and this is what I do. I thought that it was a version problem but after a few upgrades the problem is still present.
I use HttpRequester to simulate the client. Everything worked fine till this morning.
Example of data sent:
{
"username": "david",
"password": "bowie",
"email": "[email protected]"
}
Then there is this code for responding:
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(logger('dev'));
app.use(expressValidator());
app.use(cookieParser());
app.use('/users', users);
then in users I just create a user:
// Creation of a user.
router.post('/create', function(req, res) {
// We check current mistakes like username or password empty.
if (!userhelper.checkCreateUserRequest(req, res)) {
return;
}
// Save the user in BDD
}
In the checkCreateUserRequest I do this:
if (req.body.username == null || req.body.password == null || req.body.email == null) {
res.status(400).json({message: "malformed request", code: 1});
return false;
}
I do other things like check if username is empty for example but I don't think it's important to paste it.
Thanks you for your responses and sorry for my bad english...
Well, you can pretty much just search bodyParser , and replace it with express !
Is bodyParser still used? This piece of middleware was called body-parser and used to not be part of the Express framework. The good news is that as of Express version 4.16+, their own body-parser implementation is now included in the default Express package so there is no need for you to download another dependency.
'bodyParser' is deprecated. // If you are using Express 4.16+ you don't have to import body-parser anymore.
You could set the correct HTTP header if you use JSON request.
Content-Type: application/json
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With