Ad

POST Request Body Is Empty On Server

I am trying to make an AJAX request from the client side javascript using XMLHttpRequest. Following is the code for it:

document.getElementById('myform').onsubmit=function(){
    var http = new XMLHttpRequest();
    var text = document.getElementById('myinput').value;
    console.log(text);
    http.onreadystatechange = function(){
        if(http.readyState === 4 && http.status === 200){
            location.reload();
        }
    };
    http.open('POST','/todo',true);
    http.setRequestHeader("Content-Type", "application/json");
    var obj = {
        item:text
    };
    http.send(JSON.stringify(obj));
}

This works fine without anny errors. However, on the server side, when I try to log the request body to the console, it shows as an empty object. Can someone help me with this? Following is the server side code for handling the post request:

app.post('/todo',urlencodedParser, function(req,res){
    console.log(req.body); // This logs an empty object to the console!
    newItem = Todo(req.body);
    newItem.save(function(err,data){
        if(err) throw err;
        res.json(data);
    });
});
Ad

Answer

JSON encoding and URL encoding are different.

If you wish to send the data with JSON encoding, then you must receive it with the appropriate middleware:

const bodyParser = require('body-parser');

app.post('/todo', bodyParser.json(), function(req,res){
    console.log(req.body); // This logs an empty object to the console!
    newItem = Todo(req.body);
    newItem.save(function(err,data){
        if(err) throw err;
        res.json(data);
    });
});

It most likely worked with jQuery because urlencoding is default behavior for $.post.

Ad
source: stackoverflow.com
Ad