Apologies if worded awkwardly, but I have to make an rest API call using jQuery. I've already made the call using angularJS before, but for this case I can't use that. I tried translating it to jQuery but I'm not getting the same results. Is there anything I'm doing wrong or am I missing information? I'm fairly new to jQuery so I feel as if I'm missing something crucial or misunderstood something.
Working code with angularJS:
var req = {
method: 'POST',
url: 'https://fakeurl.com/rest/v1/portal/user/' + $scope.email.value,
headers:{
'Content-Type': 'application/json',
'Header_1': 'Yes',
'x-access-token': 'glsFromWebsite' //$scope.authInfo.token
}
};
restCall($http, req).then(function (res) {
// check for error even though 200 response
if (res.error) {
console.error("Error reported...");
} else {
` //enter success code here
}
});
var restCall = function(http, req) {
var _url = getBaseUrl() + req.url;
req.url = _url;
return new Promise(function(fulfill, reject) {
try {
http(req).then(function (res) {
// check for error even though 200 response
if (res.data.error) {
if (res.data.error === '601') {
console.error('Token is invalid or has expired');
} else {
console.error("Error from end point: " + res.data.error);
}
}
fulfill(res.data);
}, function(err) {
console.error('Error calling rest endpoint',err);
reject();
});
} catch (ex) {
console.error('Exception calling rest endpoint',ex);
reject(ex);
}
});
};
My failing jQuery code:
var processCreate = function (email) {
$.ajax({
url: 'https://fakeurl.com/rest/v1/portal/user/' + email.value,
type: 'POST',
headers: {
'Content-Type': 'application/json',
'Header_1': 'Yes',
'x-access-token': 'glsFromWebsite' //$scope.authInfo.token
},
success: function (res, a, b) {
if (res === 'NOT FOUND') {
//code that runs when this case is true
} else {
//code that runs when this case is false
}
},
error: function () {
console.error("Error...");
}
});
}
Try making an ajax call like this
var processCreate = function (email) {
var authHeaders = {};
authHeaders.Authorization = 'Bearer ' + 'glsFromWebsite';
$.ajax({
url: 'https://fakeurl.com/rest/v1/portal/user/' + email.value,
type: "POST",
cache: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
headers: authHeaders,
success: function (data) {
//console.log(data);
if (data === 'NOT FOUND') {
//code that runs when this case is true
} else {
//code that runs when this case is false
}
},
error: function (xhr) {
console.log(xhr);
}
});
}
Related
After a successful login, the returned value is always false. I'm using the default Authentication system that's provided by Microsoft.Identity ("Individual User Accounts" option) with no modifications. Any thoughts?
[HttpGet]
[Route("get-userId")]
public bool CurrentUserId()
{
return User.Identity.IsAuthenticated;
}
Client-side codes:
Login.html:
$(document).ready(function () {
$('#btnLogin').click(function () {
$.ajax({
url: '/token',
method: 'POST',
contentType: 'application/json',
data: {
username: $('#txtUsername').val(),
password: $('#txtPassword').val(),
grant_type: 'password'
},
success: function (response) {
sessionStorage.setItem("accessToken", response.access_token);
window.location.href = "Momo.html";
},
error: function (jqXHR) {
$('#divErrorText').text(jqXHR.responseText);
$('#divError').show('fade');
}
});
});
});
Momo.html:
$(document).ready(function () {
if (sessionStorage.getItem('accessToken') == null) {
window.location.href = "Login.html";
}
$.ajax({
url: '/api/Account/get-userId',
method: 'GET',
success: function (response) {
console.log(response);
}
});
console.log(response) returns false.
You need to send the token to the server with each request. Add the following to your Ajax call:
headers: { "Authorization": 'Bearer ' + token }
You can rewrite your code like this:
$(document).ready(function () {
var token = sessionStorage.getItem('accessToken');
if (token == null) {
window.location.href = "Login.html";
}
$.ajax({
url: '/api/Account/get-userId',
method: 'GET',
headers: { "Authorization": 'Bearer ' + token },
success: function (response) {
console.log(response);
}
});
I implement user-defined exception in javascript code but it is not catching the exception.
I am providing my code :
function sendRequest(URL, Data, authorization, requestType,cuboidName) {
var Response = new $.Deferred();
var json;
if (requestType.toString() == "GET") {
$.ajax({
url: URL,
type: "GET",
dataType: "json",
headers: {
'Authorization': authorization,
'Accept': 'application/json'
},
success: function (result) {
Response.resolve(result);
//console.log("Response : " + JSON.stringify(result) + "\n\n\n");
},
error: function(err){
throw new Error("Error Code:\t"+err.status+"\nReason:\tCuboid Download failed for Cuboid:"+cuboidName);
}
});
}
return Response.promise();
}
I am calling the sendRequest function from the following code :
async loadDatatypeCuboid(dataCuboid)
{
try
{
dataTypeCuboiId = "444";
var res3 = new $.Deferred();
Utils.sendRequest(this.baseUrl+"rest/v1/grid/"+dataTypeCuboiId+"?importTid=-1&view=LATEST&mode=0&baselineId=-1", null, Globals.authorization, "GET","Datatype").then(function (result) {
res3.resolve(result);
if (result.status == 500) {
return;
}
else{
}
});
return res3.promise();
}
catch (error)
{
console.log(error);
}
}
I am not able to catch the thrown error. The console is showing as :
Utils.js:26 Uncaught Error: Error Code: 500 Reason: Cuboid Download
failed for Cuboid:Datatype
can anyone suggest How to Handle Exceptions in JavaScript Promise?
Thanks in Advance
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;
}
};
I am trying to pass json string from angularjs to my websrvice and used below code.Can someone please let me where i went wrong with the below code?
Controller method:
[httpget]
public string BulkData(JObject jObjectData)
{
var x = jObjectData;
return (jObjectData != null ) ? “SUCCESS”: “FAIL”;
}
Javasctiprt method :
function Get(url, data) {
var getReq = {
method: "GET",
url: url,
dataType: 'json',
data: JSON.stringify(data),
headers: { "Content-Type": "application/json;charset=UTF-8" }
};
return $http(getReq).then(function (response) {
$log.debug('**response from EXECUTE:', response);
return response;
}, function (error) {
$log.error('**error from EXECUTE', error);
return error;
});
}
You need [HttpPost] method, and make post request
Controller method:
[HttpPost]
public string BulkData(JObject jObjectData)
{
var x = jObjectData;
return (jObjectData != null ) ? “SUCCESS”: “FAIL”;
}
Javasctiprt method :
function Get(url, data) {
var getReq = {
method: "POST",
url: url,
dataType: 'json',
data: JSON.stringify(data),
headers: { "Content-Type": "application/json;charset=UTF-8" }
};
return $http(getReq).then(function (response) {
$log.debug('**response from EXECUTE:', response);
return response;
}, function (error) {
$log.error('**error from EXECUTE', error);
return error;
});
}
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;
}
}