Request Header is not updated successfully from interceptor angular 2/4 (401 handling)

筅森魡賤 提交于 2019-12-07 04:48:25

问题


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.


回答1:


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`)
});


来源:https://stackoverflow.com/questions/48200491/request-header-is-not-updated-successfully-from-interceptor-angular-2-4-401-han

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!