Express bodyParser not working properly
Asked Answered
C

2

9

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...

Conall answered 12/2, 2017 at 17:5 Comment(2)
Could you add a code snippet with an example data you are sending please?Fein
Thanks you for your response, I've updated my postConall
M
18

You could set the correct HTTP header if you use JSON request.

Content-Type: application/json

Magaretmagas answered 14/3, 2017 at 15:8 Comment(2)
You're right, after some investigation I found that my REST client was not configured properly. I use the default addon provided by firefox and I think I didn't configure it properly. With postman and an angular application it works. Thanks for your answerConall
This really shouldn't be the right answer, but as someone who uses express somewhat infrequently, I'm always forgetting to send the right headers (express's lack of errors in this case don't help!) and have been reminded of my mistake multiple times by this answer.Cuckooflower
S
3

For anyone using Express v4.16+, body-parser is no longer needed as a third-party dependency. Express has its own built-in body parser that can be used like so:

Server.js

const express = require('express')
const app = express()
app.use(express.json())
app.use(express.urlencoded({extended: false}))

In my case, initializing my app this way still resulted in an empty object (i.e. {}) being logged for req.body. I found the following packages to also be helpful

npm i cors
npm i path

And those can be used by including the following in server.js (or your respective file)

app.use(cors())
app.use(express.static(path.join(__dirname, 'public')))

You may also find it necessary to include the 'Content-Type': 'application-json' header in your fetch request from your client.

Samadhi answered 1/6, 2022 at 15:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.