Reputation: 19138
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!!
Upvotes: 23
Views: 19928
Reputation: 36777
$.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})}
)
Upvotes: 41