设置标头授权的Angular拦截器会导致api返回错误

时间:2016-02-19 19:15:04

标签: java angularjs jersey authorization angular-http-interceptors

我创建了一个拦截器来设置标头授权:

.config(['$httpProvider', function($httpProvider) {
    var httpAuthInterceptor = [ 'AuthStateService', function(AuthStateService) {
      return {
        'request': function(config) {
          var user = AuthStateService.getCurrentUser();
          var token = AuthStateService._getToken();
          if (token) {
            config.headers['Authorization'] = 'Basic' + user + ':' + token;
          }
          return config || $q.when(config);
        }
      };
    }];

    $httpProvider.interceptors.push(httpAuthInterceptor);
}]);

所以,当我调用下面的服务时,服务(数据)的返回是OK的3次(OKOKOK)。

.factory("connectAPI", ['$http', 'config', 'loginAPI', function($http, config, loginAPI){
  var _connect = function(callBack){
    var param = {
        user: loginAPI.getUser(),
        pass: loginAPI.getPass()
      };

    $http.get(config.baseUrl + 'connect/user/' + param.user + '/pass/' + param.pass)
      .success(function(data){
        callBack(data);
      })
      .error(function(data, status, headers, config){
        console.log(data, status, headers, config);
      });
  };

  return {
    connect: _connect
  };
}])

我的api方法:

@Path("user/{user}/pass/{pass}")
@GET
@Produces({ MediaType.APPLICATION_JSON  + ";charset=utf-8"})
public String getUserData(@PathParam("user") String user, @PathParam("pass") String pass) {
  if (user != "" && pass != ""){
    //test
    return "OK"
  }
  return "NOK"
}

我已经检查过了,api方法正在调用3次。我不知道发生了什么。

当我评论标题授权行时,api方法只调用一次。有什么问题?

.config(['$httpProvider', function($httpProvider) {
    var httpAuthInterceptor = [ 'AuthStateService', function(AuthStateService) {
      return {
        'request': function(config) {
          var user = AuthStateService.getCurrentUser();
          var token = AuthStateService._getToken();
          //if (token) {
          //  config.headers['Authorization'] = 'Basic' + user + ':' + token;
          //}
          return config || $q.when(config);
        }
      };
    }];

    $httpProvider.interceptors.push(httpAuthInterceptor);
}]);

1 个答案:

答案 0 :(得分:0)

我意识到这是我的web.xml中的一个问题,我无意中复制了我的过滤器。