Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 475
Startec Avatar asked Jan 09 '23 11:01

Startec


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');
    }
})
like image 66
huwence Avatar answered Jan 22 '23 05:01

huwence


Mine was not working too, but solved by using,

contentType: 'application/json',
data: JSON.stringify(formdata),
like image 22
Eiconic Avatar answered Jan 22 '23 05:01

Eiconic