繁体   English   中英

在AngularJS中的401上获取响应对象

[英]Getting response object on 401 in AngularJS

我正在使用Angular 1.6.4,Express 4.15.2和express-session。 我试图通过检查req.session.user参数的存在来捕获用户是否未经授权访问特定路由。 如果不是,我想发送401响应状态并在Angular中更改状态。

问题是我没有得到任何响应对象来检查其状态。 我尝试使用拦截器,注销error.response.body,真正注销所有内容以查找丢失响应对象的位置。

这是一些代码,任何帮助将不胜感激!

表达:

app.get('/update', sessionCheck, function(req, res) {
  res.send('session');
});

function sessionCheck(req, res, next){
    if(req.session.user) {
      next();
    } else {
      console.log('before');
      return res.status(401).send('Unauthorized');
      console.log('after');
    }
}

角度:

.state('update', {
  url: '/update',
   views: {
    "": {
      templateUrl: 'templates/update.html',
      controller: function($http) {
        return $http.get('/update').then(function(response) {
          console.log('Ok response' + response);
        }, function(error) {
          console.log('Error response' + error.response.body);
        });
      },
    },
    "carousel": {
      templateUrl: "templates/carousel.html"
    },
    "footer": {
      templateUrl: "templates/footer.html"
    }
  }
})

网络画面

您是否尝试过使用拦截器来做到这一点?

您可以通过以下方式尝试:

anyModule.service('yourInterceptor', function($q) {
var service = this;

service.responseError = function(response) {
    if (response.status == 401){
        //do something
    }
    return $q.reject(response);
};

})

请注意,这里我们正在处理responseError

您还需要在配置函数中注册拦截器:

$httpProvider.interceptors.push('yourInterceptor');

您可以查看此内容以获取有关此拦截器的更多信息:

使用Angular.js拦截器捕获HTTP 401

更新:

您也可以通过这种方式注册拦截器:

app.factory("YourInterceptor", ["$q", "$rootScope", "$location",
function($q, $rootScope, $location) {
    var success = function(response) {
        //do something
        return response;
    },
    error = function(response) {
        if(response.status === 401) {
                // do something
        }

        return $q.reject(response); //reject on error
    };

    return function(httpPromise) {
        return httpPromise.then(success, error);
    };
}

然后以这种方式(在模块的配置中)注册拦截器:

$httpProvider.responseInterceptors.push("YourInterceptor");

请注意,您可以在responseInterceptors中推送拦截器。 这项工作对我来说。

暂无
暂无

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

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