Javascript promise wait for AccessToken value - javascript

I got huge problem with understanding values i got function which getting array with access token and I passing this token to ajax url to get json data. I know I need to use there promise to run ajax after I get access token. Could you help me with this one ?
componentDidMount: function () {
var component = this;
var accessToken = getAccessToken();
$.ajax({
type: 'GET',
url: window.APIUrl +'services/?access_token=' + accessToken,
dataType: 'json',
success: function(response)
{
component.setState({
services : response
});
}
});
}
function getAccessToken(){
var client_id = '****',
client_key = '****',
$ = jQuery;
if(!window.accessToken){
$.ajax({
url : APIUrl + 'auth',
method : 'post',
data : {
'id' : client_id,
'key' : client_key
},
success: function(response){
if(typeof response.access_token != 'undefined'){
/*console.log(response);*/
window.accessToken = response.access_token;
return response.access_token;
}else{
return false;
}
}
});
}else{
return window.accessToken;
}
}

Make your function getAccessToken to return a promise
componentDidMount: function () {
var component = this;
getAccessToken()
.then(function(accessToken) {
var url = window.APIUrl +'services/?access_token=' + accessToken,
return $.getJSON(url)
})
.then(function(response) {
component.setState({
services: response
});
});
}
function getAccessToken(){
if(window.accessToken) {
return $.when(window.accessToken)
}
return $.ajax(...) // get access token from server
}

Try something like this
componentDidMount: function () {
var component = this;
getAccessToken().then(function(accessToken) {
$.ajax({
type: 'GET',
url: window.APIUrl +'services/?access_token=' + accessToken,
dataType: 'json',
success: function(response)
{
component.setState({ services : response });
}
});
})
}
function getAccessToken(){
var deferred = $.Deferred()
var client_id = '****',
client_key = '****',
$ = jQuery;
if(!window.accessToken){
$.ajax({
url : APIUrl + 'auth',
method : 'post',
data : {
'id' : client_id,
'key' : client_key
},
success: function(response){
if(typeof response.access_token != 'undefined'){
/*console.log(response);*/
window.accessToken = response.access_token;
deferred.resolve(window.accessToken)
} else {
deferred.reject()
}
}
});
} else {
deferred.resolve(window.accessToken)
}
return deferred.promise()
}

Related

how to return data in a nesting function

I am trying to return function after check user existed and not existed
var data = checkUser();
alert(data);
// return a data after check user
function checkUser(){
$.ajax({
type : "get",
url : "checkuser",
data : {
username : username,
},
success: function(){
return "ok";
},
error : function(){
return "error";
}
});
}
Its better to use callback in this scenario:
var myCallback = function(data){
alert(data);
};
checkUser(myCallback);
Your ajax would be :
function checkUser(callback){
$.ajax({
type : "get",
url : "checkuser",
data : {
username : username,
},
success: function(){
callback("ok");
},
error : function(){
callback("error");
}
});
}
Kindly read more on callback function
You will need to use async and await if your nested function is an asynchronous function.
One way is to do this:
async function checkUser(){
try {
const result = await fetch("checkuser",{data:username});
alert("ok");
} catch (err) {
alert("error");
}
}

Async function unexpected behavior

At the moment I am working on an Electron app that is supplied with data via an API. The renderer calls a "backend function", which first gets the API key via Keytar and then executes the API call via axios.
The problem here is that Keytar always returns null/undefined, even if a similar function with the same functionality works without any problems, also because this point can only be reached if a valid API key is stored at all and this will also be queried by Keytar.
I am new to async/await-functions, maybe I didn't get something.
btw: Maybe the title doesn't fit too well, but I was a bit at a loss about this one.
(keytarService, username, baseUrl are globals)
Here is my code:
// Api-calling function
async function makeCall(method_type, url_path, data_array) {
keytar.getPassword(keytarService, username).then((apiKey) => {
if (apiKey == null || apiKey == undefined) {
return false;
}
axios({
method: method_type,
url: baseUrl + url_path,
headers: {
'content-type': 'application/json',
'X-AUTH-TOKEN': apiKey,
},
data: data_array,
}).then(
(response) => {
return response.data;
},
(error) => {
return false;
}
);
});
}
//index_renderer.js
webContents.on('dom-ready', () => {
apiMain
.makeCall('GET', 'user/self')
.then((data) => {
console.log(data);
document.getElementById('username_text').innerText =
data.firstName + '' + data.lastName;
})
.catch((err) => console.log(err));
});
Similar function which is working:
async function isAuthenticated() {
apiKey = await keytar.getPassword(keytarService, username);
if (apiKey == null || apiKey == undefined) {
return false;
}
axios({
method: 'GET',
url: baseUrl + '/api/isAuthenticated',
headers: {
'content-type': 'application/json',
'X-AUTH-TOKEN': apiKey,
},
data: {},
}).then(
(response) => {
console.log(response);
if (!response.data.authenticated) {
logout();
}
return response;
},
(error) => {
console.log(error);
logout();
return error;
}
);
}
// call of the working function in main.js
if (authProcess.isAuthenticated()) {
mainwin.loadFile('index.html');
} else {
mainwin.loadFile('login.html');
}
Thanks in advance.
You are missing important returns in MakeCall().
Try:
function makeCall(method_type, url_path, data_array) {
// return this promise to MakeCall
return keytar.getPassword(keytarService, username).then((apiKey) => {
if (apiKey == null || apiKey == undefined) {
return false;
}
// return this promise to keytar.getPassword then()
return axios({
method: method_type,
url: baseUrl + url_path,
headers: {
'content-type': 'application/json',
'X-AUTH-TOKEN': apiKey,
},
data: data_array,
}).then(
(response) => {
return response.data;
},
(error) => {
return false;
}
);
});
}

how to cache ajax response in browser and retrieve value from cache browser

I want to cache ajax response into browser database so that i can retrieve the reponse from another web page of the same application.
so far i have tried but i am not able to retrieve the data from browser cache.
any help will be appreciated
this my setting.js
appsetting = {
service1: 'http://localhost:59190/api/Settings/GetConfigurationSettings',
settingsdata: {},
savesettings: function (data) {
//alert('success');
console.log(data);
appsetting.settingsdata = data;
},
getsettings: function () {
var token = { 'token': '00000000-0000-0000-0000-000000000000' };
DBconnection.fetchdata('GET', appsetting.service1, appsetting.savesettings, function () { console.log('Cannot fetch pos') }, token, true);
}
}
this is ajaxcall.js
DBconnection = {
localCache: {
timeout: 30000,
data: {},
remove: function (url) {
delete DBconnection.localCache.data[url];
},
exist: function (url) {
return !!DBconnection.localCache.data[url] && ((new Date().getTime() - DBconnection.localCache.data[url]._) < DBconnection.localCache.timeout);
},
get: function (url) {
console.log('Getting in cache for url' + url);
return DBconnection.localCache.data[url].data;
},
set: function (url, cachedData, callback) {
DBconnection.localCache.remove(url);
DBconnection.localCache.data[url] = {
_: new Date().getTime(),
data: cachedData
};
if ($.isFunction(callback)) callback(cachedData);
}
},
fetchdata: function (typeofcall, url, success, failure, header, cachedata) {
$.ajax({
type: typeofcall,
url: url,
dataType: 'json',
failure: failure,
success: success,
headers: header,
cache: cachedata
});
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
if (options.cache) {
var complete = originalOptions.complete || $.noop,
url = originalOptions.url;
//remove jQuery cache as we have our own localCache
options.cache = false;
options.beforeSend = function () {
if (DBconnection.localCache.exist(url)) {
complete(DBconnection.localCache.get(url));
return false;
}
return true;
};
options.complete = function (data, textStatus) {
DBconnection.localCache.set(url, data, complete);
};
}
});
}
}
on my webpage i am trying to call like this
var setting = appsetting.getsettings();
console.log(setting);
but i am getting undefined result.

Code issue with AngularJS and JSON

I have a JSON source and want to get results from it with a post request.
When I test with POSTMAN extension in chorme it works really well. But when I do that with angularJS the page keep loading and chrome consoles shows errors.
My code is here:
angular.module('loginApp', []).controller('loginController', function ($scope, $http) {
$scope.userName = '';
$scope.userPass = '';
$scope.output = function () {
var params = JSON.stringify({
username: '******',
password: '******'
});
$http({url: "http://xx.xx.xx.xx/api/user/login.json",
method: 'POST',
data: params,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then(function (response) {
return response;
});
};
});
Any help would be appreciated :)
try this, and after post error if occured:
var LoginApp = angular.module('loginApp', []);
LoginApp.controller('loginController', function ($scope, $common) {
$scope.userName = '';
$scope.userPass = '';
$scope.output = function () {
var params = JSON.stringify({
username: '******',
password: '******'
});
$common.ajax("http://xx.xx.xx.xx/api/user/login.json", params, "POST").then(function (response) {
console.log(response);
return response;
});
};
});
LoginApp.factory("$common", function($http, $q) {
function ajax(url, param, method) {
var request = $http({
method: method,
url: url,
data:param
});
var promise = request.then(
function(response) {
return(response.data);
},
function(response) {
console.log("Ocurred error: " + response);
return($q.reject("Something went wrong"));
}
);
return promise;
}
return({
ajax:ajax
});
});
Try this:
$scope.output = function () {
var params = {
username: '******',
password: '******'
};
$http.post("http://xx.xx.xx.xx/api/user/login.json", params)
.then(function (response) {
return response;
});
};
Also you should move your http request to a service. It's a bad practice put it in a controller.

How to re try operation after refresh token - jquery ajax

In my flow say i am using an access token for getting my data. When my access token expires i get a 401 error i am using the refresh token to get a new access token.
Note : My access token and refresh token is stored in a cookie and i am updating the same after a 401 error.
My question how do i retry the same operation which i was in the middle of?
My Code (services.js):
var refresh_token = "na";
function get_api_data(url, api_token) {
var returnData = handleApiData(url, api_token, "GET");
return returnData;
}
function post_api_data(url, api_token, post_data) {
var returnData = handleApiData(url, api_token, "PUT", post_data);
return returnData;
}
function handleApiData(url, access_token, type, post_data) {
return $.ajax({
url: url,
type: type,
data: post_data,
error: failHandler,
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + access_token);
}
})
}
function handleData(data, textStatus, jqXHR) {
return data;
}
function failHandler(jqXHR, textStatus, errorThrown) {
switch (jqXHR.status) {
case 401:
var api = get_api_token();
checkApiToken(api.refresh_token);
break;
default:
alert(errorThrown);
}
}
function checkApiToken(refresh_token) {
if (refresh_token != "na") {
$.post("/Account/Refresh/?refresh_token=" + refresh_token);
//location.reload();
}
}
My Code (notification.js):
$(function () {
var api = get_api_token();
if (api != null)
get_notification_data(api.access_token);
});
function get_notification_data(api_token) {
var notifications = get_api_data(urls.notifications.list, api_token);
if (notifications != undefined)
notifications.success(function (data) {
items = data.records;
_.each(items, function (item) {
item.Status = ko.observable(item.status);
item.onClick = function () {
if (item.Status() === 'UNREAD') {
var post_data = { id: item.id };
post_api_data(urls.notifications.list, api_token, post_data).success(function (response, textStatus) {
if (response.success)
item.Status('READ');
$(location).attr("href", item.action_link);
});
}
else {
$(location).attr("href", item.action_link);
}
}
});
var model = {
items: ko.observableArray(items),
onCancel: function (item) {
}
}
ko.applyBindings(model, $("#notificationBar")[0]);
})
}
Edit: My AccountController code that sets the new API cookie:
[HttpPost]
public ActionResult Refresh(string refresh_token)
{
string token_string = string.Empty;
try
{
token_string = OAuthHelper.getTokenViaRefreshTokenFromAPIServer(refresh_token);
if(token_string != null)
Response.Cookies[Constants.Cookies.API].Value = token_string;
}
catch (Exception ex)
{
Log.Info(string.Format("AccountController.cs -Refresh Token Error ", ex.Message));
}
return RedirectToAction("Index","Home");
}

Categories