无法从拦截器角度2/4成功更新请求标头(401处理) [英] Request Header is not updated successfully from interceptor angular 2/4 (401 handling)

查看:133
本文介绍了无法从拦截器角度2/4成功更新请求标头(401处理)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Http拦截器,并尝试重试失败的请求以处理401 error.我正在尝试设置一个新的标头来更新请求,但是它不起作用.

我注意到我的标头没有与请求一起设置,而是转到标头内的lazyUpdates.谁能提供给我任何想法,为什么会这样.检查我的网络后,我发现通过重试请求传递的旧标头为'x-auth-token',并且不发送新标头.

interceptor.ts

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        request = request.clone({
            setHeaders: {
                'x-auth-token': this.authService.getToken()
            }
        });

        return next.handle(request).do(event => {}, err => {
            if (err instanceof HttpErrorResponse && err.status == 401) {

                request = request.clone({
                    setHeaders: {
                        'Content-Type': 'application/json',
                        'Authorization': 'sample-auth'
                    }
                });

                return next.handle(request)
            }
        });
    }

包含在延迟加载中的值而不是标头的标头:

我已经通过此链接

有什么想法吗?

我仍然遇到同样的问题.有人可以建议我如何正确更新标头.

解决方案

我认为问题在于克隆请求.您需要执行以下操作.

request = request.clone({
     headers: request.headers.set("Authorization", `sample-auth`)
});

I am working with Http interceptor and trying to retry the failed request to handle 401 error. I am trying to set a new header to update the request but it's not working.

I noticed that My header is not being set with the request instead it's going to the lazyUpdates inside headers. Can anyone provide me the any idea why it's happening. After checking my networks I found that with the retry request old header is passed which is 'x-auth-token' and new headers are not sent.

interceptor.ts

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        request = request.clone({
            setHeaders: {
                'x-auth-token': this.authService.getToken()
            }
        });

        return next.handle(request).do(event => {}, err => {
            if (err instanceof HttpErrorResponse && err.status == 401) {

                request = request.clone({
                    setHeaders: {
                        'Content-Type': 'application/json',
                        'Authorization': 'sample-auth'
                    }
                });

                return next.handle(request)
            }
        });
    }

Header that contains values in lazy loading instead of headers:

I have already gone through this link

Any ideas?

I am still having same issue. would anyone please suggest me what can be done to update headers properly.

解决方案

I think the problem is with cloning of the request. You need to do something like this.

request = request.clone({
     headers: request.headers.set("Authorization", `sample-auth`)
});

这篇关于无法从拦截器角度2/4成功更新请求标头(401处理)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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