Startec
Startec

Reputation: 13206

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?

Upvotes: 4

Views: 12121

Answers (4)

Eiconic
Eiconic

Reputation: 4306

Mine was not working too, but solved by using,

contentType: 'application/json',
data: JSON.stringify(formdata),

Upvotes: 6

onekay
onekay

Reputation: 11

This may be a late reply, but please also note the JQuery ajax documentation:

Object must be Key/Value pairs.

This took me 2 hours (server received empty body) because I was trying to post a more 'complicated' object.

Upvotes: 1

huwence
huwence

Reputation: 326

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

Upvotes: 5

easywaru
easywaru

Reputation: 1153

Check following api

By setting the processData option to false, the automatic conversion of data to strings is prevented.

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

Jquery processData

Upvotes: 1

Related Questions