Angular JS 发送通用 headers 和 http post 重定向

Angular JS send common headers with http post redirect

我正在使用 angular js 和 node express 使用 jwt 作为身份验证机制。我在 angular 中使用 http post 作为 post 我的用户名和密码,它成功生成了 jwt 令牌。但无法重定向任何其他页面。如何通过 angular JS 在其他页面中将该标记设置为 header。

我的 angular 控制器是,

  var app = angular.module('authenticate', []);

  app.controller('AuthenticateCtrl', function($scope, $http) {

      $scope.login = function() {
          option={'name':$scope.name,'password':$scope.password}
          $http({
          method : "POST",
          url : "/api/authenticate",
          data:option
          }).then(function mySucces(response) {
          $scope.message = response.data;
          //$scope.getData(response.data);
          $http.defaults.headers.common['x-access-token'] = response.data;
          window.location.href = '/api/home';
          alert("You are logged in.!");
          }, function myError(response) {
          $scope.message = response.statusText;
          //console.log(response.data);
          console.log(response.statusText);
          var alertPopup = $ionicPopup.alert({
              title: 'Login failed!',
              template: 'Please check your credentials!'
          });
          });
          }

  });

HTML脚本是,

  <body ng-controller="AuthenticateCtrl">
  <div class="container">
  <h2>.</h2>
    <input type="text" name="name" ng-model="name" placeholder="Name" required="" autofocus="" class="form-control" /></p>
    <input type="password" name="password" ng-model="password" placeholder="Password" required="" class="form-control" /></p>
    <button ng-click="login()" class="btn btn-lg btn-primary btn-block">Login</button>
    <hr />
    {{ message }}
</div>
  </body>

并且 POST 请求处理节点 js 部分是,

apps.get('/home', function(req, res, next) {
    res.sendFile(dirname+'/public/home.html');
    });

但是重定向的主页显示

{"success":false,"message":"No token provided."}

留言。这是我的身份验证失败消息。 任何人都请帮我解决这个问题。

您应该使用 an interceptor to set the x-access-token and you should use routing 进行导航。您不应使用 window.location.href 在 Angular SPA 中导航。

示例拦截器如下所示:

app.factory('sampleInterceptor', ['$location', function ($location) {
    var sampleInterceptorFactory = {};
    var _request = function (config) {
        config.headers = config.headers || {};
        config.headers['x-access-token'] = authData;
        return config;
    }
    sampleInterceptorFactory.request = _request;
    return sampleInterceptorFactory;
}]);

示例路由器如下所示:

app.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/home', {
        templateUrl: 'templates/home.html',
        controller: 'HomeController'
      }).
      when('/login', {
        templateUrl: 'templates/login.html',
        controller: 'LoginController'
      }).
      otherwise({
        redirectTo: '/login'
      });
  }]);