首页 > 解决方案 > Angular 5 - HTTP拦截器拦截401作为状态码0

问题描述

我目前无法像大多数应用程序一样拦截 401 状态并重定向到登录页面,我的拦截几乎是样板文件

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        request = request.clone({
            withCredentials: true
        });

        return next.handle(request)
        .pipe(
            retry(0),
            takeUntil(this.httpCancelService.onCancelPendingRequests()), ==> cancels out pending request on route change
            catchError((error: HttpErrorResponse) => {
                if (error.status === 401) {
                    this.authenticationService.logout() ===> logout incase of 401     
                }  else if (request.url.indexOf("assets") == -1) {
                    this.alertService.error('An unexpected error occurred, please try again later');
                }

                return throwError(errorMessage)
            })
        )
    }

浏览器在“网络”选项卡上将请求捕获为 401,但在这个 Angular 拦截器上,我们得到“error.status”为“0”和“error.message”为“未知错误”

标签: htmlcssangularhttp

解决方案


状态码 0 表示可能是 CORS 错误。这意味着来自后端服务器的响应缺少Access-Control-Allow-Origin标头。正确配置后端后,您将能够访问实际的错误代码。


推荐阅读