Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POSTing json to express using jQuery

Tags:

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

like image 400
Ed_ Avatar asked May 11 '13 14:05

Ed_


1 Answers

$.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})} ) 
like image 162
soulcheck Avatar answered Sep 18 '22 14:09

soulcheck