POSTing json to express using jQuery

19,626

$.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})}
)
Share:
19,626

Related videos on Youtube

Ed_
Author by

Ed_

Developer & business owner (pixelnebula.com) Always on the lookout for great JavaScript developers - if you're looking for a job in the UK drop an email with your CV to: #SOreadytohelp

Updated on June 14, 2022

Comments

  • Ed_
    Ed_ almost 2 years

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

  • Christiaan Westerbeek
    Christiaan Westerbeek about 10 years
    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.
  • Viet
    Viet over 6 years
    @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
  • codemonkey
    codemonkey over 4 years
    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.