nag*_*hun 7 http-status-code-302 angular
我使用 spring security,它将未经身份验证的用户重定向到登录页面。
因此,当未经身份验证的 Angular 客户端向端点(期望 JSON)发送 GET 请求时,它接收到登录页面的 HTML 内容,并且 JSON 解析器失败(Angular2 watch for 302 redirect when fetching resource)
const httpObservable = this.http.get(urlThatWillRedirect).subscribe(data => ...) // JSON parser will fail
Run Code Online (Sandbox Code Playgroud)
如何在 Angular 中处理重定向?
在正确的解决办法是改变服务器端代码不返回302个状态码,因为在角(或任何为此事SPA)之前重定向浏览器踢腿可以做任何事情。通常,您希望为此目的返回 401/403。
如果这是不可能的,唯一的选择是实现一个黑客解决方案,以某种方式识别响应确实是一个重定向,并通过使用 HttpInterceptors 适当地处理它。这是AngularJS 中的一个等效示例。
在 Angular 2+ 中,您可能可以按照这样的操作来检查响应是否是重定向页面:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req)
.do(event => {
if (event instanceof HttpResponseBase) {
const response = event as HttpResponseBase;
if (response && response.ok && response.url && response.url.toLowerCase().indexOf(this.logoPartialUrl) >= 0) {
// Modify this portion appropriately to match your redirect page
const queryStringIndex = response.url.indexOf('?');
const loginUrl = queryStringIndex && queryStringIndex > 0 ? response.url.substring(0, queryStringIndex) : response.url;
console.log('User logout detected, redirecting to login page: %s', loginUrl);
window.location.href = loginUrl;
}
}
});
Run Code Online (Sandbox Code Playgroud)
它不是很干净,我建议使用Router和来处理路由和状态Guards。但是如果 JSON 解析器失败(这是未登录的定义,您也许可以使用错误处理程序在客户端处理重定向。
const httpObservable = this.http
.get(urlThatWillRedirect)
.subscribe(
(data) => {//handle data},
(error) => {// redirect to login page}
);
Run Code Online (Sandbox Code Playgroud)