AngularJS添加标题授权令牌

问题描述:

所以,我一直在挖过去两天,但我不知道为什么这是不行的..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://*.com/questions/24710503/how-do-i-post-urlencoded-form-data-with-http-in-angularjs – Chandermani

+0

我已经正确地转换了数据,如果我不包括头授权请求是工作,并从服务器结果JSON响应,但是当我尝试添加头授权时,它不会工作 –

+0

您可以查看网络日志中的错误。 – Chandermani

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并且我从服务器获得了该令牌已过期的错误消息 –