Interceptor Angular 4.3 - Set multiple headers on the cloned request

后端 未结 4 1683
夕颜
夕颜 2020-12-16 10:47

I just noticed that the Header Object that was possible to use in the previous HTTP RequestsOption is not anymore supported in the new Interceptor.

It\'s the new Int

4条回答
  •  伪装坚强ぢ
    2020-12-16 11:21

    To append to the existing header of a cloned request (like in an HTTP Interceptor), the code below works (using Angular 5.x). In the case below, it appends to the existing header (which in my case includes the XSRF-TOKEN cookie automatically included by Angular) with a JWT Authorization token stored in sessionStorage:

    export class TokenInterceptor implements HttpInterceptor {
    
        constructor() { }
        intercept(request: HttpRequest, next: HttpHandler): Observable> {
    
            let headers = request.headers
                .set('Content-Type', 'application/json')
                .set('Authorization', `Bearer ${sessionStorage.getItem('authToken')}`);
    
            const cloneReq = request.clone({ headers });
    
            return next.handle(cloneReq);
        }
    }
    

提交回复
热议问题