I'm working on a webpage that I need to display the list of repos by using the github api. But keep get 401 error. Not sure where I was wrong.....
Here is what I have so far:
function requestJSON(url, callback) {
$.ajax({
url: url,
dataType: "json",
complete: function(xhr) {
callback.call(null, xhr.responseJSON);
console.log(xhr.responseJSON);
//alert('Load was performed.');
if (xhr.status === 200) {
alert('User\'s name is ' + xhr.responseText);
}
else {
alert('Request failed. Returned status of ' + xhr.status);
}
},
error: function( req, status, err ) { console.log( 'something went wrong', status, err );
},
beforeSend: function(xhr, settings) { xhr.setRequestHeader('Authorization',authCredentials);
xhr.setRequestHeader('Content-Type', 'text/plain');}
});
}
});
beforeSend: function(xhr, settings) { xhr.setRequestHeader('Authorization',authCredentials);
xhr.setRequestHeader('Content-Type', 'text/plain');}
It was my authCredentials issue, miss type.....
Related
I want to call this function on button click after login and wait for result, to get token value. This function cannot be changed, it is async and supplied from other currently unavailable team.
I already tried something like this, but with no success. I get web service results, but I can't write appropriate sync call to wait to return token.
function getToken() {
param1 = "123456";
ajax_oauth(param1, function (success, response) {
success: return response.token;
});
}
function ajax_oauth(param1, callback) {
APP.debug("oauth login with param1 " + param1);
try {
APP.blockUI();
var DeviceID = APP.readRegistry(APP_CONFIG.REGISTRY.DeviceID);
//---------------------------------------------------------------
$.ajax(
auth_token_url,
{
method: "GET",
accept: 'application/json',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: JSON.stringify({
'param1': param1,
'deviceId': DeviceID
}),
xhrFields: {
withCredentials: false
},
statusCode: {
201: function (response) {
APP_STATE.hasOauth = true;
APP.debug('got response 200 from oauth');
auth.login(response.token); //TODO read expiration from token
try {
var decoded = jwt_decode(response.token);
APP_STATE.uid = decoded.uid;
} catch (err) {
APP.error("unable to decode token " + JSON.stringify(err));
}
},
401: function () {
},
500: function () {
},
503: function () {
}
},
success: function (response) {
APP.unblockUI();
APP_STATE.restAvailable = true;
},
error: function (jqXHR, textStatus, errorThrown) {
APP.unblockUI();
APP_STATE.restAvailable = false;
APP.restError(auth_token_url, jqXHR, errorThrown, textStatus);
APP.callback(callback, false);
}
}
);
} catch (err) {
APP.error("unable to do oauth login, " + err);
}
};
After user clicks on login button, I want to call function ajax_oauth and to return token if params ok. If not, to return login error. Login can't be async, as far as I can see.
For whatever reason you can't tap into the original ajax response, you could intercept the request using $.ajaxPrefilter.
From your code it looks like auth_token_url has a global reference. You could use this to intercept the call by matching the outgoing request on the resource URL.
$.ajaxPrefilter('json', function(options, originalOptions, jqXHR) {
if (options.url === auth_token_url) {
jqXHR.done(function(response) {
try {
var decoded = jwt_decode(response.token);
console.log(decoded);
} catch (err) {
APP.error("unable to decode token " + JSON.stringify(err));
}
});
}
});
Note that this needs to be declared well before the request is made preferably after jQuery is loaded.
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 configure my Backbone router with different views. But on some views, I need to fetch a collection. If the user is not logged in, server returns a 401 http status.
So, I configure jQuery's global ajax settings like that:
$.ajaxSetup({
xhrFields: {
withCredentials: true
},
crossDomain: true,
error: function(jqXHR, textStatus, errorThrown) {
console.log("error ajax");
if (jqXHR.status == 401) {
console.log('error 401');
app.router.navigate('', { trigger: true });
}
}
});
But it never goes in the error callback, even if the response code is 401.
Instead of modifying the ajax options globally, I modified Backbone.sync function to handle authentication.
Backbone.sync = (function(syncFn) {
return function(method, model, options) {
options = options || {};
var beforeSend = options.beforeSend,
error = options.error;
// Add headers
options.beforeSend = function(xhr) {
xhr.setRequestHeader('withCredentials', true);
if (beforeSend) return beforeSend.apply(this, arguments);
};
// handle unauthorized error (401)
options.error = function(xhr, textStatus, errorThrown) {
console.log("error sync");
if (error) error.call(options.context, xhr, textStatus, errorThrown);
if (xhr.status === 401) {
console.log('error 401');
app.router.navigate('', { trigger: true });
}
};
return syncFn.apply(this, arguments);
};
})(Backbone.sync);
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);
}
});
}
I am using the jQuery.get() method
$.get('login.php', function(d, textStatus, jqXHR){
//alert(jqXHR.status)
var status = jqXHR.status;
if((status==200)||(status==202)){
window.location.href = 'dashboard.html';
}else if(status==401){
alert('Error in login details')
}else{
alert('Unknown Error')
}
});
It is working fine. When 200 & 202 , It will rediredt to dashboard page. But Other than 200 & 202, It pass the error in console but doesn't show alert.
You need to add in some event handlers for the fail state, which will handle 4xx and 5xx errors. The success state only handles HTTP codes which indicate a successful request. From http://api.jquery.com/jQuery.get
var jqxhr = $.get( "example.php", function(data, status) {
alert( "success - " + status );
})
.done(function(data, status) {
alert( "second success - " + status );
})
.fail(function(data, status) {
alert( "error - " + status );
})
.always(function(data, status) {
alert( "finished - " + status );
});
This is because the callback function you have defined is only called when a successful request completes. If the response is anything other than a 200, the request is considered to have errored. To do what you require, you could use the $.ajax() method:
$.ajax({
url: 'login.php',
success: function() {
window.location.assign('dashboard.html');
},
error: function(xhr) {
if (xhr.status == 401) {
alert('Error in login details')
} else {
alert('Unknown Error')
}
}
});