2015-06-21 75 views
0

我想在每次發出請求時在標頭中傳遞我的令牌。我現在做的方式是使用:AngularJS簡單認證攔截器

$http.defaults.headers.common['auth_token'] = $localStorage.token; 

我怎麼能做到這一點,使發送到每一個要求,當它拋出一個錯誤,應該做一個

$state.go('login') 
+0

使用它的run方法文檔ñ谷歌是烏拉圭回合的朋友https://docs.angularjs.org/api/ng/service/$http – swapnesh

+0

你的意思是這樣 的.config(函數($ httpProvider){$ http.defaults.headers.common ['auth_token'] = $ localStorage.token; }) $ state.go出現錯誤時怎麼辦@swapnesh – teddybear123

+0

或者通過這個http://stackoverflow.com/a/ 27136594/639406 – swapnesh

回答

2

如果你想添加您的令牌到每個請求,並回應任何錯誤,您最好的選擇是使用Angular HTTP攔截器。

符合您的需求,它可能是這個樣子:

$httpProvider.interceptors.push(function ($q, $state, $localStorage) { 
    return { 

    // Add an interceptor for requests. 
    'request': function (config) { 
     config.headers = config.headers || {}; // Default to an empty object if no headers are set. 

     // Set the header if the token is stored. 
     if($localStorage.token) { 
     config.headers.common['auth_token'] = $localStorage.token; 
     } 

     return config; 
    }, 

    // Add an interceptor for any responses that error. 
    'responseError': function(response) { 

     // Check if the error is auth-related. 
     if(response.status === 401 || response.status === 403) { 
     $state.go('login'); 
     } 

     return $q.reject(response); 
    } 

    }; 
}); 

希望這有助於。

+0

寫得很好+1 – swapnesh