How Node.js https post JSON field looks in jquery format? - javascript

My question is Node uses request.write to send JSON post request and jquery's AJAX uses the 'data' field. Do I understand it right?
Here my node.js
const apiToken = "eae5819bd5e14803a1abff8141c36ee6";
const contentJSON = JSON.stringify({
'contestId': "0ac3ac99-0509-456a-8ff6-9f193048c4f3",
'contesttype': "OverUnder",
'direction': "moon",
'wager': "0.001"
});
const https = require('https');
const options = {
hostname: 'beta.hxro.io',
port: 443,
path: '/hxroapi/api/ContestEntry/add-contest-entry',
method: 'POST',
headers: {
'Content-Type':'application/json',
'Ocp-Apim-Subscription-Key': 'agh383j89dh93ij9',
}
}
const req = https.request(options, (res) => {
res.on('data', (d) => {
console.log(JSON.parse(d));
});
});
req.on('error', (error) => {
console.error(error);
});
req.write(contentJSON);
req.end();
This is what I think in jQuery it will look like:
contentJSON = {
contestId: contestId,
userId: "AB",
contesttype: "OverUnder",
direction: "moon",
wager: "0.00005"
};
console.log(contentJSON);
$.ajax({
type: "POST",
url: "https://beta.hxro.io/hxroapi/api/ContestEntry/add-contest-entry",
data: JSON.stringify(contentJSON),
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Content-Type": "application/json",
"Ocp-Apim-Subscription-Key": "sa77euhe83ji40ie"
},
success: function(data) {
console.log(data);
},
failure: function(errMsg) {
alert(errMsg);
}
});
Node's one works but not the jquery. JS solutions are welcome.

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,

Implement clientside token-based authentication using plain Javascript/AJAX

Can anyone point me to an article that explains clientside token auth implementation using Javascript?
I found many articles on Angular but that is not what I'm looking for. That brings me to the question if it is possible to be done with Javascript.
Also how to handle scenarios when the auth server throws a 401. Is there a built in exception to detect that response? Or is a custom exception required to be implemented?
I have personally used JSON web tokens in one of my projects.
http://blog.slatepeak.com/creating-a-simple-node-express-api-authentication-system-with-passport-and-jwt is a tutorial on how to set up JSON web tokens on the server side.
Once you get the token as a response to the client side, you can store the token on window.localStorage.
var credentials = {
username : document.getElementById("username").value,
password : document.getElementById("password").value
};
var url = window.localStorage.getItem('appUrl');
$.ajax({
url: url + '/register',
type: 'POST',
data: { username: credentials.username, password: credentials.password },
success: function(Data) {
window.localStorage.setItem('token', Data.token);
},
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', window.localStorage.getItem('token'));},
error: function() {
alert('Error occured');
}
});
});
Then you can attach it in an AJAX call as a header while navigating to other pages.
$.ajax
({
type: "GET",
url: "index1.php",
data: '{}',
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization',window.localStorage.getItem('token'));
},
success: function (){
alert('Thanks for your comment!');
}
});
This worked for me..
var token = gettoken();
function getDatatypes() {
if (isEmpty(token)) {
token = gettoken();
}
var request = getDatatypesFromApi();
request.success(function (data) {
alert('success!');
});
request.error(function (httpObj, textStatus) {
if (httpObj.status == 401)
gettoken();
});
}
function getDatatypesFromApi() {
var request = $.ajax
({
type: "GET",
url: "http://yoururl.com/",
data: '',
headers:{
'Authorization': 'Basic ' + token
},
dataType: "json",
timeout: 5000,
});
return request;
}
function gettoken() {
var credentials = {
username: "userid",
password: "PASS",
domain: "",
extensionsAppId:"{extAppId}"
};
var url = "http://thelinktoresource/"
$.ajax({
url: url,
type: 'GET',
data: { userId: credentials.username, password: credentials.password, domain: credentials.domain, extensionsAppId: credentials.extensionsAppId },
dataType: "json",
contentType: 'application/json; charset=UTF-8',
success: function (Data) {
console.log(Data);
token = Data.replace(/"/ig, '');
return token;
},
error: function () {
alert('Error occured');
return "undefined";
}
});
}
function isEmpty(strIn) {
if (strIn === undefined) {
return true;
}
else if (strIn == null) {
return true;
}
else if (strIn == "") {
return true;
}
else {
return false;
}
}

$http get null when use phone browser

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

Get data from ajax request to Angular

I have 2 requests
$.ajax({
type: "POST",
url: "http://sandbox.gasvisor.com:9988/uaa/oauth/token",
data: "grant_type=client_credentials",
headers: { 'Content-Type': 'application/x-www-form-urlencoded',
'Authorization':'Basic SVRXRV9XRUJfQVBQOml0d2VfY2xpZW50' },
success:function(data){
console.log(data);
getData(data.access_token);
}
})
function getData(acess_token){
$.ajax({
type: "GET",
url: "http://sandbox.gasvisor.com/api/v2/gobjects/search/withinRadius?longitude=24.711117&latitude=48.922633&radius=10",
headers: {
'Authorization':'bearer'+acess_token },
success:function(data){
console.log(data);
}
})
}
They return json from server. I need to get data from Json file to my Angular listing. Pls help me.
Here is a simple example for one of your call:
$http({
method: 'POST',
url: 'http://sandbox.gasvisor.com:9988/uaa/oauth/token',
data: 'grant_type=client_credentials',
headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization':'Basic SVRXRV9XRUJfQVBQOml0d2VfY2xpZW50' },
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
$scope.response = response;
}, function errorCallback(err) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.error = err;
});

Categories

Resources