2016-04-21 112 views
1

所以,我一直在挖過去兩天,但我不知道爲什麼這是不行的..AngularJS添加標題授權令牌

這裏的問題,我儘量讓請求的API服務器和我必須在請求中添加一個令牌,但是當我將令牌添加到頭授權時,我得到了服務器的響應405

這個api我測試過郵遞員及其工作,但是當我實現角度它不起作用

這是我的代碼:

$http({ 
      method: 'POST', 
      url: url, 
      data: data, 
      headers: { 
       "Authorization": "Bearer xxxxxxxxxxx", 
       "Content-Type": "application/x-www-form-urlencoded" 
      } 
     }) 

,這是由鉻中的req頭: img

所以在這種情況下,這是我的代碼,或服務器的問題?

+0

一個問題,我看到的是,你正在做一個窗體-urlencoded後不標準的JSON職位。數據需要轉換。看到這裏http://stackoverflow.com/questions/24710503/how-do-i-post-urlencoded-form-data-with-http-in-angularjs – Chandermani

+0

我已經正確地轉換了數據,如果我不包括頭授權請求是工作,並從服務器結果JSON響應,但是當我嘗試添加頭授權時,它不會工作 –

+0

您可以查看網絡日誌中的錯誤。 – Chandermani

回答

0
angular 
    .module('app') 
    .factory('authInterceptor', authInterceptor); 
authInterceptor.$inject = ["$q","$location"]; 
function authInterceptor($q, $location) { 
     return { 
      // Add authorization token to headers 
      request: function (config) { 
      // get token from a cookie or local storage 
      var token = "token string "; 
      config.headers = config.headers || {}; 
      config.headers.Authorization = "Bearer " + token; 
      return config; 
      }, 
      // Intercept 401s and redirect you to login 
      responseError: function(response) { 

      if(response.status === 401) { 
      // redirect to some page 

       // remove any stale tokens 
       return $q.reject(response); 
      } 
      else { 
       return $q.reject(response); 
      } 
      } 
     }; 
     } 

再注入攔截這樣

$httpProvider.interceptors.push('authInterceptor'); 
+0

仍然錯誤,405法不允許的:'( –

+0

也許您正在使用該令牌無效或過期 –

+0

即使令牌正確過期至少其返回JSON並且我從服務器獲得了該令牌已過期的錯誤消息 –