Reputation: 13206
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
Reputation: 4306
Mine was not working too, but solved by using,
contentType: 'application/json',
data: JSON.stringify(formdata),
Upvotes: 6
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
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
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
Upvotes: 1