如何找出AngularJS中拒绝html模板的状态码?
如果用户未经授权,如何在如何找出AngularJS中拒绝html模板的状态码?,angularjs,Angularjs,如果用户未经授权,如何在$routeChangeError中获取响应的状态代码-401,并使用AngularJS重定向到正确的路由 $rootScope.$on("$routeChangeError", function(event, next, current, rejection) { var status = //how to get the status code? if(status===401) $location.path("/401"); }); 我有一个旅
$routeChangeError
中获取响应的状态代码-401
,并使用AngularJS重定向到正确的路由
$rootScope.$on("$routeChangeError", function(event, next, current, rejection) {
var status = //how to get the status code?
if(status===401) $location.path("/401");
});
我有一个旅行路线:
$routeProvider
.when("/office/workspaces", {
templateUrl: "partials/office/workspaces",
controller: "OfficeWorkspacesCtrl"
});
以下服务器路由:
router.get("/workspaces", Identity.isAuthenticated, function(request, response) {
response.render("office/workspaces", {});
});
以下是经过身份验证的函数:
module.exports.isAuthenticated = function(req, res, next) {
var isAuthenticated = util.isObject(req.identity);
if (isAuthenticated) {
return next();
} else {
return res.status(401).send();
}
};
对于您的任务,有更好的解决方案。使用
$httpProvider.interceptors
。有关此解决方案的文档:
用于全局错误处理、身份验证或任何类型的
请求或请求的同步或异步预处理
在对响应进行后处理时,最好能够拦截
在将请求移交给服务器之前进行请求,并在提交之前进行响应
它们被移交给启动这些应用程序的应用程序代码
请求
在主模块中,创建工厂:
app.factory('myHttpInterceptor', ['$q', '$location', function ($q, $location) {
return {
responseError: function(rejection) {
switch(rejection.status){
case 401:
$location.path("/401");
break;
case 0:
// actions when internet is down
break;
default:
// some default actions
}
return $q.reject(rejection);
}
};
}]);
然后在应用程序配置中
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('authHttpInterceptor');
});
其中app为varapp=angular.module(…
您可以在文档$http中阅读,对于您的任务,有更好的解决方案。使用
$httpProvider.interceptors
。有关此解决方案的文档:
用于全局错误处理、身份验证或任何类型的
请求或请求的同步或异步预处理
在对响应进行后处理时,最好能够拦截
在将请求移交给服务器之前进行请求,并在提交之前进行响应
它们被移交给启动这些应用程序的应用程序代码
请求
在主模块中,创建工厂:
app.factory('myHttpInterceptor', ['$q', '$location', function ($q, $location) {
return {
responseError: function(rejection) {
switch(rejection.status){
case 401:
$location.path("/401");
break;
case 0:
// actions when internet is down
break;
default:
// some default actions
}
return $q.reject(rejection);
}
};
}]);
然后在应用程序配置中
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('authHttpInterceptor');
});
其中app为varapp=angular.module(…
您可以在文档$http中了解它