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

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?

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

Mine was not working too, but solved by using,
contentType: 'application/json',
data: JSON.stringify(formdata),

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

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.

Related

How to update outlook 2.0 API token using refresh-token?

I have next situation:
Main authentication flow happens on server, then client side obtains these data, since that moment I wanna client be able to update token by itself. It's seems there is all needed data on client(access_token, refresh_token), but I can't figure out how to organize request to https://login.microsoftonline.com/common/oauth2/v2.0/token route.
First I tried to get json response:
$.ajax({
url: `https://login.microsoftonline.com/common/oauth2/token?grant_type=refresh_token&refresh_token=refresh_token&scope=openid%20profile%20offline%20access%20user.read%20mail.read%20contacts.read%20calendars.read&client_id=client&client_secret=secret`,
type: 'POST',
cache: false,
processData: false,
contentType: false,
dataType: 'json',
headers: {
'Host': 'https://login.microsoftonline.com',
'Content-Type': 'application/json'
},
success: function(data) {
...
},
error: function(xhr) {
...
}
});
After that I figured out that it's only possible to get this data with redirect, is it correct? If it is, can someone produce an example of how to implement this, looks like it's needed to create an iframe and handle authorization somehow. Thanks.
UPDATED:
as Alina Li pointed in comment to her answer, there is a solution right in the official doc https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow
According to my test, you could using refresh-token through the below code:
var data = "grant_type=refresh_token&refresh_token=refreshToken&client_id=" + appState.clientId;
$http = $http || $injector.get('$http');
$http.post(authUrl + '/token', data, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function (response) {
}).error(function (err, status) {
});
You don’t need to add scope parameter.
Reference from:
Storing Refresh Token In JavaScript, Getting New Access Token

Receiving Jquery POST data in Express

Edit See the accepted answer below for the fix. I also had to remove the line contentType: 'appliction/json', from my POST request.
I'm trying to send a string to Node.js / Express, but req.body is undefined server-side.
Client jQuery:
$.post({
traditional: true,
url: '/matches',
contentType: 'appliction/json',
data: viewedProfiles,
dataType: 'json',
success: function(response){
Express:
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.post('/matches', isLoggedIn, function(req, res){
console.log(req.body) // this is undefined
var loadedProfiles = []
loadedProfiles.push(req.body.viewedProfiles)
console.log('loadedProfiles')
console.log(loadedProfiles)
I've tried:
not specifying 'dataType'
setting data: JSON.stringify(viewProfiles)
splitting the string into an array on the client, and then having jQuery stringify it
looking for req.params instead of req.body (clutching at straws)
I can see the XHR request in dev tools, and it contains the string I'm expecting.
What super obvious thing am I missing to send the data to Express?
Thanks.
Your server side code looks fine but you need to use $.ajax() rather than $.post() function because $.post() function send data into url (with url encoded). So your JQuery code would be
$.ajax({
url: '/matches',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({"viewedProfiles": viewedProfiles}),
success: function(response){
I hope this will help you
I've configured an exact same setup. And code below works:
var profiles = { 'data' : 'hello' };
$.post({
traditional: true,
url: '/matches',
contentType: 'application/json',
data: JSON.stringify( profiles ),
dataType: 'json',
success: function(response){ console.log( response ); }
} );
My nodejs engine:
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.post( '/matches' , function(req, res){
console.log(req.body) // this outputs: { data: 'hello' }
} );
Btw, There is a typo where your contentType is, 'applicAtion/json'

Javascript & Node.js - make a JSON request

in this Question I read that in node.js you can distinguish between html requests and json requests like so:
app.get('/route', function (req, res) {
if (req.is('json')) res.json(data);
else if (req.is('html')) res.render('view', {});
else ...
});
now my question is how do you make a request that is interpreted as json in node server?
cause I tried with $.ajax and $.getJson and typed in the browser and all were html requests.
this is my request
$.ajax({ type: 'GET', url: "/test", dataType:"json", success: function(data){log(data)}})
The req.is method checks the incoming request type by inspecting the Content-Type header therefore you need to make sure this header is set in the request before it's sent up e.g.
$.ajax({
type: 'GET',
url: '/route',
contentType: "application/json; charset=utf-8",
....
});
However, the Content-Type header is used to determine the format of the request body, not the response. It's recommended you use the Accept header instead to inform the server of what type of format is appropriate for the response e.g.
app.get('/route', function (req, res) {
if (req.accepts('html')) {
res.render('view', {});
} else if (req.accepts('json')) {
res.json(data);
} else {
...
}
});
Then on the client, you don't need to worry about the Content-header but rather the Accept header, and jQuery already provides a handy little method for that
$.getJSON('/route', function(data) {
...
});
Try setting the contentType parameter
$.ajax({
type: 'GET',
url: 'your_url',
data: {
test: "test"
},
contentType: "application/json; charset=utf-8",
dataType: "json",
....
});
EDIT:
You can use the request Module
all you have to do is
var request = require('request');
var options = {
uri: 'your_server_side_url',
method: 'POST',
json: {
"data": "some_data"
}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body.id) // Print the shortened url.
}
});
Check out that github link. May be that module will make your life easier

AJAX is not sending request

I have the following code:
$("form").submit(function()
{
//Checking data here:
$("input").each(function(i, obj)
{
});
alert(JSON.stringify($(this).serializeArray()));
var url='http://127.0.0.1:1337/receive';
$.ajax({
url: url,
type: 'POST',
contentType:'application/json',
data: JSON.stringify($(this).serializeArray()),
dataType:'json'
});
});
And after I submit the form, I get a JavaScript alert with the json string, so that is made correct (on my server I only log it so it does not matter what it is in it). If I try to send a request to the same link from postman it works, it logs it.
I think I'm doing something wrong in the ajax call, but I am not able to figure out.
Try below piece of code. Add success and error handler for more details
$("form").submit(function()
{
//Checking data here:
$("input").each(function(i, obj)
{
});
alert(JSON.stringify($(this).serializeArray()));
var url='http://127.0.0.1:1337/receive';
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify($(this).serializeArray()),
dataType:'json',
success : function(response) {
alert("success");
},
error: function (xhr, status, error) {
alert(error);
}
});
});
data:{ list : JSON.stringify($(this).serializeArray())}
From the Jquery docs:
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
crossDomain attribute simply force the request to be cross-domain. dataType is jsonp and there is a parameter added to the url.
$.ajax({
url:'http://127.0.0.1:1337/receive',
data:{ apikey: 'secret-key-or-any-other-parameter-in-json-format' },
dataType:'jsonp',
crossDomain: 'true',
success:function (data) {alert(data.first_name);}
});

"400 Bad Request" response for AJAX request

I have the following jQuery AJAX request:
// collect form data and create user obj
var user = new User();
user.firstname = $("#usrFirstName").val();
user.lastname = $("#usrSurname").val();
user.role = $("#usrRole").val();
// actual ajax request
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: user,
contentType:"application/json; charset=utf-8",
dataType: 'json'
}).done(function(data, status) {
alert(JSON.stringify(data));
}).fail(function(data, status) {
alert(status);
alert(JSON.stringify(data));
});
The response from the Server is:
"status":400,"statusText":"Bad Request"
"The request sent by the client was syntactically incorrect."
The server is running Spring-MVC. But as far as I can tell it is working correctly. Because if I'm sending a request manually with Postman and the following configuration it works.
Header:
Content-Type application/json; charset=utf-8
Content:
{"firstname":"alex","lastname":"lala","role":"admin"}
I have to mention that it is a cross-domain request (for the time developing, it will be hosted on the same domain as the server later). I did disable the security settings in the browser and AJAX requests to the server are working fine (as long as I don't have to send data).
you need to serialize your json, try:
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user),
contentType:'application/json; charset=utf-8',
dataType: 'json'
})
JSON.stringify() method is used to turn a javascript object into json string. You need to have this. In addition it is better to include success and error portions in the AJAX.
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user), // turn a javascript object into json string
contentType:'application/json; charset=utf-8',
dataType: 'json',
success: function (html) {
alert(html);
}, error: function (error) {
alert(error);
}
})

Categories