CmdrDoom
CmdrDoom

Reputation: 55

JSON body always empty in Node.js application

I am building a simple application using Node.js. On the client, I am sending some JSON data using Ajax to the server with the following code:

var data = {};
data.title = "title";
data.message = "message";
$.ajax({
    type: 'POST',
    data: JSON.stringify(data),
    contentType: 'application/json',
    url: '/myresult',
    processData: false,
    success: function (data) {
        console.log('success');
        console.log(JSON.stringify(data));
    }
});

The server side code handling this request is:

app.post('/myresult', function (req, res) {
    var obj = {};
    console.log('body: ' + JSON.stringify(req.body));
    res.send(req.body);
});

However the console log prints the response bode as empty, i.e. body: {}.

Why is the body value empty and how can it be filled with the title and message?

Upvotes: 0

Views: 1246

Answers (1)

Selfish
Selfish

Reputation: 6190

Express gets a kind help from body-parser. Use it as a middleware to get the actual body content:

app.use(require('body-parser').urlencoded({extended: true}));

and then leave your code as it was:

app.post('/myresult', function(req, res) {
    var obj = {};
    console.log('body: ' + JSON.stringify(req.body));
    res.send(req.body);
});

I expect this will work for you, but please note bodyParser.json() as well, which might be better suited for your needs.


In addition, what's currently happening is since you have processData: false, it's basically sending this: ({"command":"on"}).toString() which is [object Object] and there's your body parser failing. Try removing processData flag entirely.

Upvotes: 1

Related Questions