0
我使用AngularJS來構建單頁面應用程序。我希望代碼AnggularJS部分總是檢查身份驗證情況,每當有數據連接到服務器時總是發送頭部信息[X-Access-Token]。下面是我使用的代碼,但它可能有問題,因爲它不起作用。我必須用手將頭部X-Access-Token的數據添加到函數$ http get,post中。你有任何AngularJS的經驗,請幫助我!謝謝。Angular.js App的驗證API
app.factory('myHttpResponseInterceptor',['$q','$location',function($q,$location){
return function (promise) {
var success = function (response) {
return response;
console.log(response);
};
var error = function (response) {
if (response.status == 401) {
//$state.go('signin');
}
return $q.reject(response);
};
return promise.then(success, error);
};
}]);
//Http Intercpetor to check auth failures for xhr requests
app.config(['$httpProvider',function($httpProvider) {
$httpProvider.interceptors.push('myHttpResponseInterceptor');
}]);
app.factory('api', function ($http, $cookieStore, flash, $state) {
return {
init: function (token) {
$http.defaults.headers.common['X-Access-Token'] = token || $cookieStore.get('token');
}
};
});
app.run(function (api) {
api.init();
});
app.controller('adminProCatController', function($scope, $rootScope, flash, $state, $http, $cookieStore) {
$http.get('api/v1/categories?image_size=50x50', {headers: {'X-Access-Token': $cookieStore.get('token')}}).success(function(data) {
$scope.categories = data;
});
});