xavatic
xavatic

Reputation: 185

Express bodyParser not working properly

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

Upvotes: 9

Views: 15492

Answers (2)

Digglit
Digglit

Reputation: 686

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.

Upvotes: 3

Kiss Robert
Kiss Robert

Reputation: 259

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

Content-Type: application/json

Upvotes: 18

Related Questions