$http get null when use phone browser - javascript

I use $http to make a POST request to get my imugur access token, and everything work fine on my PC browser.
But when I use my android phone(ios not sure, haven't tried it), I get an error and from the console.log I see NULL.
I have no idea how to fix this, can anyone help?
Thanks
$http({
method: 'POST',
url: "https://api.imgur.com/oauth2/token",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: { client_id: "my_cliendID", client_secret: "my_clientSecret", grant_type: "refresh_token", refresh_token: "my_refreshToken" }
}).success(function (e) {
callback(e);
}).error(function (e) {
console.log(e);
});
=========================================================.
when I use $http I get the NULL value, so I try to use $resource but still the same issue. PC work fine, but when use phone I still get an error from function (error) {alert(JSON.stringify(error))}); now I get some response instead of NULL value. (refer to image)
var token = $resource("https://api.imgur.com/oauth2/token", null, {gettoken: {method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded'}}
function getAccess(callback) {
data= { client_id: "my_cliendID",
client_secret: "my_clientSecret",
grant_type: "refresh_token",
refresh_token: "my_refreshToken"
}
var toke = token.gettoken($httpParamSerializer(data),
function (success) {
alert(JSON.stringify(success))
responseSuccess(success, null, callback)
},
function (error) {
alert(JSON.stringify(error))
responseError(error, callback)
});
};

after I tried with jquery ajax, it work on both side(PC & mobile)
Don't know why angular $http & $resource not working on mobile browser.
data= { client_id: "client_id",
client_secret: "client_secret",
grant_type: "refresh_token",
refresh_token: "refresh_token"
}
$.ajax({
type: "POST",
url: 'https://api.imgur.com/oauth2/token',
data: $httpParamSerializerJQLike(data),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
success: function(res) {
callback(res);
},
error:function(res){
}
});

Related

Getting 400 Bad Request on axios post call

I'm using a url shortner API to test connecting to a API and I keep getting a 400 BadRequest. I've read through a dozen posts here and tried all suggestions and still nothing will work. I don't know what I'm doing wrong.
Function
var axios = require('axios');
module.exports = function (callback, data) {
let url = 'https://cleanuri.com/api/v1/shorten';
let axiosConfig = {
"headers": {
'Content-Type': 'application/json;charset=UTF-8'
}
};
let longUrl = { "url" : data };
axios(url, {
method: "post",
params: {
"url" : data
},
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
}
})
.then(function (response) {
callback(null, response.data);
}).catch(function (err) {
console.log("error: " + err.response);
callback(err, null);
});
I've also tried this and got same error
axios.post(url, JSON.stringify(longUrl), axiosConfig)
.then(function (response) {
callback(null, response.data);
}).catch(function (err) {
console.log("error: " + err.response);
callback(err, null);
});
To send data as body use data field on request options
const payload = { ... }
axios({ ..., data: payload })
params field is used to send query string within url
I have read your api docs https://cleanuri.com/docs.
That requiring your payload send as body, so use data field
Here the snippet:
let payload = { "url" : data };
axios(url, {
method: "post",
data: payload,
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
}
})
Edit:
400 Bad Request is indicating your request is invalid (by server)

GMAIL API sending reply with file attachment

I'm currently working on gmail API base on this thread
https://stackoverflow.com/a/31792244/6766279
everything works fine if I just need to compose a new email, but I don't know how to do it if i need to reply. i tried changing the data with threadId, and receives an error, 'Recipient address required.'
/* Send the mail! */
$.ajax({
type: "POST",
url: "https://www.googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=multipart",
contentType: "message/rfc822",
beforeSend: function (xhr, settings) {
xhr.setRequestHeader('Authorization', 'Bearer ' + ACCESS_TOKEN);
},
data: {
raw: mail,
threadId: thread.id
},
success: function (res) {
resolve(res)
},
error: function (error) {
console.log('ERROR:', error.responseJSON.error.message);
window.open(`${location.origin}/api/google/rest/verify`, "", "width=500, height=500");
}
});
I really need help.
/* Send the reply! */
$.ajax({
type: "POST",
url: "https://www.googleapis.com/gmail/v1/users/me/messages/send",
headers: {
'Content-Type' : 'application/json',
'Authorization': 'Bearer ' + ACCESS_TOKEN,
},
data: JSON.stringify({
raw: btoa(mail).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''),
threadId : threadId
}),
success: function(res){
console.log(res)
},
error: function(error){
console.log('ERROR:', error);
}
});
Solved with this,

How do I pass the response of one API as a request param in another API using Request-Promise

I want to pass the response received from one API as a request parameter in another API using Request-Promise NodeJs module. Can someone pls help me in this? I am giving a brief of the sample code below:
var Sequence = {
test1: function (param) {
return request({
"method": "POST",
"uri": baseURL+"/v1/" + userID + "/test/info/",
"json": true,
"headers": {
"Accept": "application/json",
},
}).then(function (result) {
return result.pairingInfo // I want to use this pairinfInfo param in another request
})
test2 : function (param) {
return request({
"method": "POST",
"uri": baseURL+"/v1/passenger/" + userID + "/test/test/",
"json": true,
"headers": {
"Accept": "application/json",
},
"qs": {
**"pairingInfo": pairingInfo**,//This pairingInfo would come from the returned result.pairingInfo of test 1 API call
}
})
}
},
How can I achieve this?
You can use this because you have a return statement in the test1() method. So, just trigger it to get it:
"qs": {
"pairingInfo": this.test1(),
}
Sequence.test1(param)
.then(function(pairingInfo) {
Sequence.test2(pairingInfo) ;
});
// You are returning the paringInfo with the first promise, so you can use it in the .then() method.
Use this function:
const sequence = async (baseURL, userID) => {
try {
let options1 = {
method: 'POST',
uri: baseURL + '/v1/' + userID + '/test/info/',
json: true,
headers: {
Accept: 'application/json'
}
};
let pairingInfo = await request(options1);
if (pairingInfo) {
let options2 = {
method: 'POST',
uri: baseURL + '/v1/passenger/' + userID + '/test/test/',
json: true,
headers: {
Accept: 'application/json'
},
qs: {
pairingInfo: pairingInfo //This pairingInfo would come from the returned result.pairingInfo of test 1 API call
}
};
await request(options2);
return true;
} else {
console.log('Request 1 failed');
return false;
}
} catch (err) {
console.error(err);
return false;
}
};

ReferenceError: $ is not defined in angular ajax

I have written the code below:
postData: function(value1) {
return $.ajax({
method: "POST",
url: "http://my.url",
data: value1,
beforeSend: function(){},
complete: function() {
console.log("done");
}
});
}
And the error I receive is:
ReferenceError: $ is not defined
I call this service with:
Service.postData($rootScope.variable).then(function(res){
console.log(res);
});
How can I solve the aforementioned problem?
Create methods like this in angularJS Service:
someFuntion: function() {
var url = 'Your URL';
var deferred = $q.defer();
$http.get(url, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then(function(data) {
deferred.resolve(data.data);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
},

How to send a rest PUT request in angular passing body

I need to send a rest request to a web server, I am using this code :
var getData = function(...) {
return $http({
method: "PUT",
url: getStatistics,
headers: {
'loginId': ...,
'token': ...,
'Content-Type': 'application/x-www-form-urlencoded',
},
data: {"...":"...","...":"...","...":"...","...":"...",
"...":"....","....":"...",
"datefrom":"2017-01-01","dateto":"2017-10-20"}
}).then(function(result){
var dataString = JSON.stringify(result.data);
alert(result.data);
return result.data;
});
};
The problem is that I am receiving error 400 bad request, What should I do?
The request works on Postman With this structure
https://i.stack.imgur.com/BBrwF.jpg
https://i.stack.imgur.com/NbQuO.jpg
Should it be a problem of how Am I passing the data object ?
That's how I implemented the $httpParamSerializerJQLike, it it Correct?
app.factory('statistics', function($http,$httpParamSerializerJQLike) {
var getData = function(loginId,token,id,dataInizio,dataFine,periodo,selezione) {
// Angular $http() and then() both return promises themselves
var data = '{"datefrom":"2017-01-01","dateto":"2017-10-20"}';
alert(data);
return $http({
method: "PUT",
url: getStatistics,
headers: {
'loginId': loginId,
'token': token,
'Content-Type': 'application/x-www-form-urlencoded',
},
data: { 'data': $httpParamSerializerJQLike(data)}
}).then(function(result){
var dataString = JSON.stringify(result.data);
alert(result.data);
return result.data;
});
};
return { getData: getData };
});
you're sending an x-www-form-urlencoded body, but it contains a single parameter named data, containing JSON.
You thus need
data: $httpParamSerializerJQLike({data: angular.toJson(data)})

Categories

Resources