Reputation: 1200
I'm trying to figure out why the access_token
(function) variable isn't accessible from an inner scope (ie. nested inside of the global function).
Here is the code:
$(function () {
var accessToken = "";
var getHeaders = function () {
alert(accessToken);
if (accessToken) {
return {
"Authorization" : "Bearer " + accessToken
};
}
}
var showResponse = function (obj) {
$("#output").text(JSON.stringify(obj, null, 4));
};
var register = function () {
var url = "/api/account/register";
var contentBody = $("#registerData").serialize();
$.post(url, contentBody).always(showResponse);
return false;
}
var saveAccessToken = function (response) {
accesToken = response.access_token;
};
var login = function () {
var url = "/token";
var contentBody = $("#loginData").serialize();
contentBody = contentBody + "&grant_type=password";
$.post(url, contentBody)
.success(saveAccessToken)
.always(showResponse);
return false;
};
var getPatients = function () {
var url = "http://localhost:62012/api/patients/";
$.ajax(url, {
type: "GET",
beforeSend: function (xhr, settings) { xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken); }
}).always(showResponse);
return false;
};
$("#getPatients").click(getPatients);
$("#register").click(register);
$("#login").click(login);
});
I've attempted to use alerts throughout the code, but it would seem as if the accessToken
simply is ""
whenever the alert isn't fired inside saveAcessToken
...
General flow of the application:
accessToken
.ajax
GET request is sent when the user clicks the getPatients
button. Any help would be appreciated!
Upvotes: 0
Views: 49
Reputation: 51
Looks like you are setting a variable named accesToken in saveAccessToken. Try renaming it to accessToken
Upvotes: 2