Mathieu Bertin Mathieu Bertin - 1 month ago 27
Javascript Question

Sending a POST request with chai sends an empty body?

I have the following setup right now

test.js

var user = {
username: 'test_user',
email: 'test@test.me',
password: 'you shall not pass',
address: 'No where street'
};
chai.request(app)
.post('/api/v1/users')
.send(user);


I'm handling the post request in my routes/user.js

router.post('/', function(req, res, next) {
console.log('body: ' + req.body);
queries.insertUser(req.body)
.then(function(id) {
return queries.getSingleUser(id);
})
.then(function(user) {
res.status(200).json(user);
})
.catch(function(err) {
next(err);
});
});


req.body ends up being undefined. Any clue as to what might be going wrong?

The code is live at https://ide.c9.io/burtonium/node-from-scratch if anybody wants to have a look.

Answer

req.body being undefined is generally caused by either not using the body-parser middleware in Express, or declaring it incorrectly (for instance, after the route that wants to access req.body).

Assuming that Chai sends JSON, add this to your Express app:

app.use(require('body-parser').json());

(before you declare the routers)