JQuery.ajax POST request has empty body when received by Node

For some reason, when I create an ajax post with jQuery, the body fetched with 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 might be doing wrong. My browser even shows the payload and post request (object formData

), but node doesn't write anything. Any ideas?

+3


source to share


2 answers


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');
    }
})

      

+3


source


Check the following api

Setting the processData parameter to false prevents automatic data conversion to strings.



If you want to use json type, processData must be set to true

JQuery processData

+1


source







All Articles