【问题标题】:Can't remove JSON web tokens from headers for one XHR request in angular无法从 Angular 中的一个 XHR 请求的标头中删除 JSON Web 令牌
【发布时间】:2015-12-24 11:52:49
【问题描述】:

我需要使用 Web 令牌进行身份验证并访问我的 REST API。我也在尝试访问天气 API,但无法访问它,因为标头正在发送 x-access-token 并且我收到此错误:

请求头字段 x-access-token 不允许 访问控制允许标头。

我已尝试以下方法将标头令牌重置为未定义的特定请求。不幸的是,当我在浏览器控制台中检查配置对象时,用户的令牌仍然存在。请帮忙!

weatherService.js

//Make a request to GET weather by zip code
    weatherFactory.getWeather = function(zip){
      $http.get('http://api.openweathermap.org/data/2.5/forecast/city?id=524901',
                {
                  headers: {'x-access-token': undefined}
                })
        //Resolve our promise with the data requested
        .success(function(data){
          console.log(data);
        })
        //Promise will be rejected
        .error(function(err){
          console.log('Error getting data');
        });
        return $q.reject(zip);
    };//end getWeather

app.js

//./public/app/app.js
angular.module('swellsApp', [
  // 'ngAnimate',
  'appRoutes',
  'userService',
  'weatherService',
  'mainCtrl',
  'userCtrl',
  'weatherCtrl'
])
  //application configuration to integrate tokens into our requests
  .config(function($httpProvider){
    //attach auth interceptor to the http requests
    $httpProvider.interceptors.push('AuthInterceptor');
  });

authService.js

// authService.js

angular.module('authService', [])
  // ============================================
  //auth factory to login and get information
  //inject $http for communicating with the API
  //inject $q to return promise objects
  //inject AuthToken to manage tokens
  // ============================================

  .factory('Auth', function($http, $q, AuthToken){
    //create auth factory object
    var authFactory = {};

    // handle login for users
    // Post request to /api/authenticate
    authFactory.login = function(username, password){
      //return the promise object and its data
      return $http.post('/api/authenticate', {
        username: username,
        password: password
      })
        .success(function(data){
          AuthToken.setToken(data.token);
          return data;
        });
    };

    //log a user out by clearing the token useing AuthToken factory
    authFactory.logout = function(){
      //clear the token
      AuthToken.setToken();
    };

    //check if a user is logged in and check if there is a local token
    authFactory.isLoggedIn = function(){
      if(AuthToken.getToken())
        return true;
      else
        return false;
    };

    //get the logged in user
    authFactory.getUser = function(){
      if(AuthToken.getToken())
        return $http.get('/api/me');
      else
        return $q.reject({message: "User doesn't have a token"});
    };

    //return auth factory object
    return authFactory;
  })//End Auth

  // ============================================
  // factory for handling tokens
  // inject $window to store token on the client-side
  // ============================================

  .factory('AuthToken', function($window){
    var authTokenFactory = {};

    //get the token out of local storage
    authTokenFactory.getToken = function(){
      return $window.localStorage.getItem('token');
    };

    //set the token or clear the token
    //if token is passed, set token - if there is no token, clear it from local storage
    authTokenFactory.setToken = function(token){
      if(token)
        $window.localStorage.setItem('token', token);
      else
        $window.localStorage.removeItem('token');
    };

    //return auth token factory
    return authTokenFactory;
  })//End AuthToken

  // ============================================
  // application configuration to integrate token into requests
  // ============================================

  .factory('AuthInterceptor', function($q, $location, AuthToken){
    var interceptorFactory = {};

    //attach the token to all HTTP requests
    interceptorFactory.request = function(config){
      //grab the token
      var token = AuthToken.getToken();

      //If token exists then add it to the header as x-access-token
      if(token)
        config.headers['x-access-token'] = token;
        console.log(config);
      return config;
    };

    //On response errors

    interceptorFactory.responseError = function(response){
      //If server returns a 403 forbidden response
      if(response.status == 403)
        $location.path('/login');

      //return the errors from the server as a promise
      return $q.reject(response);
    }

    //return interceptorFactory
    return interceptorFactory;
  });//End AuthInterceptor

【问题讨论】:

    标签: angularjs api xmlhttprequest json-web-token


    【解决方案1】:

    当您发送令牌而不是“x-access-token”时,请尝试 headers.Authorization = "Bearer" + token;

    【讨论】:

      【解决方案2】:

      在请求拦截器中,您可以使用config.url 来查看请求是否发送到其他api。

      以下是对拦截器中现有代码的更新

      //attach the token to all HTTP requests - except weather API
      interceptorFactory.request = function (config) {
          var isWeatherAPI = config.url.indexOf('api.openweathermap.org') > -1;
          // don't modify weather api headers
          if (!isWeatherAPI) {
              //grab the token
              var token = AuthToken.getToken();
              //If token exists then add it to the header as x-access-token
              if (token) {
                  config.headers['x-access-token'] = token;
              }
          }
      
          return config;
      };
      

      【讨论】:

      • 请注意,我清理了原始答案以使其不那么冗长。就在您接受之前..最新版本略有不同
      • 您也可能想要反转它并将其设置为您的域,以防您添加任何其他 api
      猜你喜欢
      • 1970-01-01
      • 2018-07-16
      • 2012-03-09
      • 2018-10-13
      • 2017-09-22
      • 2013-08-26
      • 2018-01-17
      • 2012-01-19
      • 1970-01-01
      相关资源
      最近更新 更多