Angular 重定向时刷新浏览器
Angular refresh browser on redirect
当运行一个angularjs
应用程序时,服务器端可能会撤回用户访问权限。在这种情况下,每个请求都会产生一个 http 302 重定向和一个登录 html(无部分)页面。由于 angular 确实期望它请求的任何内容,以防访问仍然被授予,它会中断,因为它可能期望 json 字符串但得到 html 登录页面。
有什么我可以做的来捕捉这个事件(听重定向,弄清楚是否返回 html 等)并做一个 "hard" 刷新重定向 url ?
由于您无法干扰 ajax 302 响应并重定向到错误页面,因此您需要有点创意。
您可以在相关响应中添加header或不同的响应代码,并在客户端添加拦截器。
拦截器是每个 ajax request\response 都要经过的模块。
您可以添加代码来查找 header 并简单地在登录页面执行 $window.location.href
。
如果我没看错,你说的是 AngularJS 的 $http
服务。
如果这就是重点,您可以自己转换响应并检查其是否有效 JSON,如下所示:
$http({
url: '...',
method: 'GET',
transformResponse: function (reponse) {
var ret = [];//if the return stays empty, the repsonse may be HTML
try {
ret = JSON.parse(reponse);
} catch (error) {
//here you could check for the error
}
return ret;
}
}).success(function(answer){
if(answer.length === 0){//its empty, so its probably HTML
$window.location.reload();//refresh page here
return;
}
//its JSON with content!
});
当运行一个angularjs
应用程序时,服务器端可能会撤回用户访问权限。在这种情况下,每个请求都会产生一个 http 302 重定向和一个登录 html(无部分)页面。由于 angular 确实期望它请求的任何内容,以防访问仍然被授予,它会中断,因为它可能期望 json 字符串但得到 html 登录页面。
有什么我可以做的来捕捉这个事件(听重定向,弄清楚是否返回 html 等)并做一个 "hard" 刷新重定向 url ?
由于您无法干扰 ajax 302 响应并重定向到错误页面,因此您需要有点创意。
您可以在相关响应中添加header或不同的响应代码,并在客户端添加拦截器。
拦截器是每个 ajax request\response 都要经过的模块。
您可以添加代码来查找 header 并简单地在登录页面执行 $window.location.href
。
如果我没看错,你说的是 AngularJS 的 $http
服务。
如果这就是重点,您可以自己转换响应并检查其是否有效 JSON,如下所示:
$http({
url: '...',
method: 'GET',
transformResponse: function (reponse) {
var ret = [];//if the return stays empty, the repsonse may be HTML
try {
ret = JSON.parse(reponse);
} catch (error) {
//here you could check for the error
}
return ret;
}
}).success(function(answer){
if(answer.length === 0){//its empty, so its probably HTML
$window.location.reload();//refresh page here
return;
}
//its JSON with content!
});