我试图拦截http响应并重定向任何401 s,但是下面的err对象只返回以下字符串。我本来希望至少能找到状态代码..。
401 -未经授权的详细信息:http://localhost:4200/api/foo的Http故障响应: 401未经授权
在“网络”选项卡中,我可以看到服务器正在返回格式良好的401。关于我如何正确阅读它们,有什么想法吗?
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authRequest = request.clone({
setHeaders: {
Authorization: `Bearer ${this.authService.getToken() || ''}`
}
});
return next.handle(authRequest).do(event => { }, err => {
if (err instanceof HttpErrorResponse && err.status === 401) {
this.authService.handleAuthentication();
}
});
}编辑:我刚刚注意到,如果我关闭web服务器强制504网关超时,我得到的错误作为一个完整的字符串,没有错误代码。
504 -网关超时详细信息:http://localhost:4200/api/foo的Http故障响应: 504网关超时
发布于 2017-12-22 22:10:19
好的,这里的问题是,我有一个预先存在的错误拦截器,它在401拦截器之前修改响应。这家伙把一切都搞砸了。感谢以上所有的回复。
发布于 2017-12-16 06:02:06
尝试使用catch
return next
.handle(authReq)
.do(event => {
if (event instanceof HttpResponse) {
/* Make your code here */
}
})
.catch((err) => {
if (err.status === 401 && err.statusText === 'Unauthorized') {
}
return Observable.throw(err);
});发布于 2017-12-16 08:46:10
通过执行以下操作,我能够使我的Auth阻断器在角度5中正确地工作:
auth.interceptor.ts
import { Injectable } from '@angular/core';
import {
HttpErrorResponse,
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest,
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { AuthService } from '../services/auth.service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(
private authService: AuthService
) { }
public intercept(
req: HttpRequest<any>,
next: HttpHandler,
): Observable<HttpEvent<any>> {
return this.authService.getToken().flatMap((token: string) => {
return next.handle(req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }));
}).do(() => { }, (error: any) => {
if (error instanceof HttpErrorResponse && (error as HttpErrorResponse).status === 401) {
this.authService.login();
}
});
}
}https://stackoverflow.com/questions/47842939
复制相似问题