我的应用程序中也遇到了同样的问题。
您无法真正“捕获”302 重定向响应。浏览器会在 Angular 处理之前捕获它。所以实际上,当您收到回复时 - 已经太晚了。
坏消息:这在角度平台上不是问题。 xmlHttpRequest 不支持这种行为,并且浏览器会在您执行任何操作之前采取行动。
参考:防止 Xmlhttprequest 重定向 https://stackoverflow.com/questions/228225/prevent-redirection-of-xmlhttprequest
好消息:有很多方法可以绕过这个问题,通过拦截响应并找到某种方法来识别这是您可爱的 302。这是一个 hack,但这是您目前可以做的最好的事情。
So.例如,在我的应用程序中,重定向回到应用程序的login.html页面,在应用程序中我得到了状态为200的响应,响应的数据是我的login.html页面的内容。
所以在我的拦截器中,我检查结果是否是一个字符串(通常不是!所以-没有效率问题..),如果是的话-检查它是否是我的login.html页面。这样,我就可以捕获重定向并按照我的方式处理它。
yourApp.factory('redirectInterceptor', ['$location', '$q', function($location, $q) {
return function(promise) {
promise.then(
function(response) {
if (typeof response.data === 'string') {
if (response.data.indexOf instanceof Function &&
response.data.indexOf('<html id="ng-app" ng-app="loginApp">') != -1) {
$location.path("/logout");
window.location = url + "logout"; // just in case
}
}
return response;
},
function(response) {
return $q.reject(response);
}
);
return promise;
};
}]);
然后将此拦截器插入到您的应用程序中。像这样的东西:
$httpProvider.responseInterceptors.push('redirectInterceptor');
祝你好运。