我从网上复制了以下代码来使用 JWT 授权,但它不起作用。特别是 $location.path
命令没有影响 - 不会发生重定向。我也尝试过使用 $state.go
,但这导致了更大的错误。我不完全理解 $q
在这里指的是什么,而不是等待 promise 解除的内容,但问题是 $location.path
不带用户返回登录屏幕(下面关于 $state
更改的建议也不是)。
$httpProvider.interceptors.push(function($q, $location, $localStorage) {
return {
'request': function (config) {
config.headers = config.headers || {};
if ($localStorage.token) {
config.headers.Authorization = 'Bearer ' + $localStorage.token;
}
return config;
},
'responseError': function(response) {
if(response.status === 401 || response.status === 403) {
console.log("app.js: httpInterceptor caught authorisation status response");
delete $localStorage.token;
$location.path('/'); // to login page
// $state.go('login');
}
return $q.reject(response);
}
};
});
}
为了进行测试,我发送了一条会导致服务器错误的消息,在返回时在开发工具中捕获该错误,然后手动设置 response.status = 403
。重定向已明确解析,但不会导致重定向。我可以看到登录屏幕被放回到屏幕上,但随后立即被不同的 View 覆盖。
这是工厂 $http ajax 请求。 我在这里使用的deferred
$q
是否可能会干扰拦截器中的内容?
$http(httpObj)
.success(function (response) { // returns 0: mongo resto data, 1: wpserver report
console.log("%s succesful, response: %s", method, response);
if (!updateNotAdd) {
Restos.data.restos.push(response[0]); // add to local copy of data
} else {
// replace existing entry with new information
var idxToReplace = _.findIndex(Restos.data.restos, function(r) {
return r.qname === resto.qname;
});
// copy over all data from editor model to database
_.assign(Restos.data.restos[idxToReplace], resto);
}
var response = {
success: true,
id: response[0]._id,
message: response[1]
};
$rootScope.$broadcast("ajaxresponse", response);
deferred.resolve(response);
})
.error(function (msg) {
// console.log(msg);
var response = {
success: false,
message: msg
};
$rootScope.$broadcast("ajaxresponse", response);
deferred.resolve(response);
});
return deferred.promise;
最佳答案
您在此处利用 ui-router 应该不会有问题。您需要使用 $injector
服务来获取 $state
服务的引用。观察以下变化...
$httpProvider.interceptors.push(function($q, $location, $localStorage, $injector) {
return {
'request': function (config) {
config.headers = config.headers || {};
if ($localStorage.token) {
config.headers.Authorization = 'Bearer ' + $localStorage.token;
}
return config;
},
'responseError': function(response) {
if(response.status === 401 || response.status === 403) {
console.log("app.js: httpInterceptor caught authorisation status response");
delete $localStorage.token;
$injector.get('$state').go('login');
}
return $q.reject(response);
}
};
});
}
您遇到的更大问题是由于 ui-router 将 $http
注入(inject) $TemplateFactory
导致的循环依赖引起的 - 导致对 的循环引用当您尝试注入(inject)
(它尚未出现在您的$state
时,$httpProvider
内的 >$http拦截器
中)无论如何注入(inject)签名)
关于javascript - $http拦截器: redirect on auth failure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31011290/