23

I'm having an issue when sending JSON data from my client to a node server running express.

Here's a simple server that demonstrates my issue:

var express = require('express');

var app = express();

app.configure(function(){   
    app.use(express.bodyParser());
    app.use(app.router);
    app.use(express.logger());
});

app.listen(80);

app.post('/', function(req,res){
    console.log(req.body);
    console.log(req.body.number + 1);
});

This server simply logs all POST data to the console.

If I then paste the following into chrome's development console: $.post('/', {number:1});

The server prints out:

{ number: '1' }
11

How can I stop the number I'm passing being interpreted as a string? Is it something to do with the bodyParser middleware I'm using?

Any help appreciated!!

1 Answer 1

41

$.post sends url-encoded data, so what is really sent is number=1, which then is parsed as well as it can by bodyParser middleware.

To send json you have to use JSON.stringify({number:1}).

Using $.post unfortunately won't set the appropriate Content-Type header (express will handle it anyway), so it's better to use:

$.ajax({
    url: '/', 
    type: 'POST', 
    contentType: 'application/json', 
    data: JSON.stringify({number:1})}
)
Sign up to request clarification or add additional context in comments.

3 Comments

And don't forget to add the contentType: 'application/json' header or there will be no data in req.body at the server at all.
@soulcheck can you please look at my question here? stackoverflow.com/questions/47085674/… it's similar to this one but i need to send another property with the array
Christiaan Westerbeek's comment on the money. Don't confuse json: true with contentType: 'application/json'. Not the same thing. Add contentType: 'application/json' if you want it to work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.