【问题标题】:Change http request header without refresh in angularjs在angularjs中更改http请求标头而不刷新
【发布时间】:2016-12-27 11:23:44
【问题描述】:

我正在编写一个使用 ngRoute 来更改页面的网站。 用于登录的表单将出现,当它成功时,控制器会在接下来的步骤中更改请求的 http 标头。 问题是当我更改标题时,如果没有重新加载页面,则不会将令牌添加到标题中。

控制器:

app.controller('catCtrl',['Api','$scope','$cookieStore','$rootScope',function (Api,$scope,$cookieStore,$rootScope) {
$scope.Login = function(){
    Api.loginEmail($scope.log_email, $scope.pass, 'chrome', 'windows','').success(function(response){
      $cookieStore.put('Auth-Key', 'Token ' + response.token);

      $scope.is_Loggedin = true;
      $scope.showLoginWin();
    }).error(function(response){
      $scope.log_email = null;
      $scope.pass = null;
      $scope.error = response.error;
    });
  };
}

应用程序运行:

app.run(['$cookieStore','$http',function($cookieStore, $http){

  $http.defaults.headers.common['Authorization'] = $cookieStore.get('Auth-Key');
}]);

如何在不重新加载页面的情况下更改标题。

【问题讨论】:

    标签: javascript angularjs http cookies


    【解决方案1】:

    所以您想在登录后根据进一步请求添加您的令牌。

    你可以试试角度拦截器。这里有几个关于如何通过拦截器添加令牌的答案。

    Interceptor Example 1

    Interceptor example 2

    示例代码:

    app.factory('httpRequestInterceptor', function () {
      return {
        request: function (config) {    
          config.headers['Authorization'] = $cookieStore.get('Auth-Key');     
    
          return config;
        }
      };
    });
    

    在您的服务层中,忽略验证此标头以进行登录。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-27
      • 1970-01-01
      • 1970-01-01
      • 2014-08-23
      • 2014-09-25
      • 2020-10-29
      • 1970-01-01
      相关资源
      最近更新 更多