Startec Startec - 4 months ago 34
jQuery Question

jQuery .ajax POST request has an empty body when received by Node

For some reason when I make an ajax post using jQuery, the body, as received by node is empty. Here is my ajax post:

jQuery

var formData = {
'order': order,
'words': 'words'
};

$.ajax({

type: 'post',

url: 'https://example.com/charge',
processData: false,
data: JSON.stringify(formData),

contentType: 'json',

xhrFields: {
withCredentials: false
},

headers: {

},

success: function (data) {
console.log('Success');
console.log(data);

},

error: function () {
console.log('We are sorry but our servers are having an issue right now');
}
})


And here is my node code:

Node

app.js


app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/', routes);


routes/index.js


router.post('/charge', function(req, res) {
console.log(req.body);
} //This always logs {}


I have no idea what I could be doing wrong here. My browser even shows a payload and the post request (the
formData
object) but node logs nothing. Any ideas?

Answer

Use ajax request like this:

          $.ajax({

                    type: 'post',
                    url: 'https://example.com/charge',   
                    data: formData,
                    xhrFields: {
                      withCredentials: false
                    },  
                    headers: {

                    }, 
                    success: function (data) {
                      console.log('Success');
                      console.log(data);

                    },  
                    error: function () {
                      console.log('We are sorry but our servers are having an issue right now');
                }
            })
Comments