Angular5 HTTP响应拦截器无法读取状态码 [英] Angular5 http reponse interceptor unable to read status code

查看:472
本文介绍了Angular5 HTTP响应拦截器无法读取状态码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图拦截http响应并重定向任何401,但是下面的err对象仅向我返回以下字符串.我原本希望至少找到状态码..

I am trying to intercept http responses and redirect any 401's but the err object below is only returning me the following string. I was expecting to at least find the status code..

401-未经授权的详细信息:的Http错误响应 http://localhost:4200/api/foo :401未经授权

401 - Unauthorized Details: Http failure response for http://localhost:4200/api/foo: 401 Unauthorized

我可以在网络标签中看到服务器返回格式正确的401.关于如何正确阅读它们有任何想法吗?

I can see in the network tab that a well formed 401 is being returned by the server. Any ideas on how I can read them correctly?

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网关超时,那么我将得到一个完整字符串且没有错误代码的错误信息.

I have just noticed that if i switch off the web server to force a 504 gateway timeout I get the error as a complete string without an error code as well.

504-网关超时详细信息:的Http失败响应 http://localhost:4200/api/foo :504网关超时

504 - Gateway Timeout Details: Http failure response for http://localhost:4200/api/foo: 504 Gateway Timeout

推荐答案

好,所以这里的问题是我有一个预先存在的错误拦截器,该错误拦截器在401拦截器之前修改了响应.这个家伙把一切都弄糟了.感谢上述所有回复.

Ok so the problem here was I had a pre-existing error interceptor that was modifying the response before my 401 interceptor. This guy was stringifying everything. Thanks to all the above responses.

这篇关于Angular5 HTTP响应拦截器无法读取状态码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆