我想检查是否存在CSRF cookie令牌,如果不存在,则重定向到登录。
没有cookie但不会触发requestError
,所以我不能把它放在那里。
我确信我可以简单地将其粘贴在request
中,但我想要“干净利落”,而不是一个脏的重定向,这会导致很多错误,可能会在控制台中冒出来,因为我重定向中间承诺链。
注意:我没有使用angular来管理身份验证。我只是让后端通过营销网站上的标准POST表单来处理它。这就是为什么它使用window.location.href
而不是$location.path()
。
$httpProvider.interceptors.push(function($q, $cookies) {
return {
request: function(config) {
if ($cookies.get(xsrfCookieName) && $cookies.get(tokenCookieName)) {
return config;
} else {
// can I do something here to redirect cleanly?
}
},
responseError: function(rejection) {
if (rejection.status === 401) {
window.location.href = '/login';
}
return $q.reject(rejection);
}
};
});
答案 0 :(得分:1)
来自docs(强调我的):
requestError:在上一个拦截器时调用拦截器 提出错误或通过拒绝解决。
因此,您可以拒绝并使用request
$httpProvider.interceptors.push(function($q, $cookies) {
return {
request: function(config) {
if ($cookies.get(xsrfCookieName) && $cookies.get(tokenCookieName)) {
return config;
} else {
return $q.reject({
status: 401
});
}
},
responseError: function(rejection) {
if (rejection.status === 401) {
window.location.href = '/login';
}
return $q.reject(rejection);
}
};
});