Jquery.post doesn’t play nice with bodyparser.json

I was recently trying to post some data to my express server with jQuery while using the npm body-parser plugin to retrieve the contents via req.body, but no matter what I did the body of my post wouldn’t show up. I’ll demonstrate why with a quick example in hope that it may save someone from making the same mistake.

Here’s an example post request straight from jquery’s documentation:

$.post('/', { name: "John", time: "2pm" })

And here’s some barebones server-side code:

var app = express();
/*** This is the troublemaker right here ***/
app.use(bodyParser.json());
app.post('/', function(req, res, next){
console.log('you made a post request to /');
console.log('request body is: ', req.body)
res.send();
});

Super simple right? But my post req.body is empty!

Why? It has to do with the preset options on the jQuery post method. The jQuery.post method is shorthand for the jQuery.ajax method:

$.post('/', { name: "John", time: "2pm" })
/*** Is the same as: ****/
$.ajax({
type: "POST",
url: '/',
data: { name: "John", time: "2pm" },
contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
  /*** Note that The default content type of an ajax post is
urlencoded even though I didn't specify it in my post ***/
});

The default contentType for ajax method is urlencoded. This means that though you don’t specify it in the method, the contentType of your $.post() request will default to ‘application/x-www-form-urlencoded; charset=UTF-8’. So you’re sending data as urlencoded from the client, but your bodyParser is expecting json on the server, so no data shows up.

Quick note - the content type in your request specifies the format that the data will be sent in, and the dataType specifies the expected type of response.

The fix is simple, you need to use the urlencoded preset for your body parser and and not the json preset. Alternatively, you could use the jQuery ajax method instead of a post and specifically set content type to ‘application/json’.

/***YES***/
app.use(bodyParser.urlencoded());
/****NO****/
app.use(bodyParser.json())

Simply replace that line in your express server code, and all of a sudden our data shows up.

W00t!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.