繁体   English   中英

AngularJS为令牌添加头部授权

[英]AngularJS Add Header Authorization for Token

所以,我一直在挖掘最近两天,但我不知道为什么这不起作用..

这是问题,我尝试向api服务器发出请求,我必须在请求中添加一个令牌,但是当我将令牌添加到头部授权时,我从服务器得到响应405

这个api我已经测试过postman及其工作,但是当我实现角度时它不起作用

我的代码:

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

这是来自chrome: img的req标题

所以在这种情况下,这是我的代码,还是服务器问题?

  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');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM