4

I want to set header for every request.

I am using request.clone for setting header in Angular 7.2.14

import { HttpInterceptor, HttpEvent, HttpRequest, HttpHandler, HttpResponse, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

export class AuthInterceptor implements HttpInterceptor {


    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {        
        const token=localStorage.getItem('token');
        console.log(token);
        request.clone({ headers: request.headers.set('Authorization', token) });    
        return next.handle(request)
    }

}


I am not getting error but I can see Authorization header

9
  • 1
    You call request.clone() but you ignore the result, which is the new, cloned request, with the header. Commented Jun 20, 2019 at 5:47
  • tried but getting error on console , blocked by CORS policy Commented Jun 20, 2019 at 5:53
  • And that's a completely different problem. Google for CORS. The response to the pre-flight request probably doesn't allow for the Authoriation header. See developer.mozilla.org/en-US/docs/Web/HTTP/CORS Commented Jun 20, 2019 at 5:57
  • Getting same error. Commented Jun 20, 2019 at 6:01
  • 1
    And I already told you that this error is a completely different problem. Google for CORS. The response to the pre-flight request probably doesn't allow for the Authoriation header. See developer.mozilla.org/en-US/docs/Web/HTTP/CORS. Fixing the frontend code won't magically fix your server configuration. Commented Jun 20, 2019 at 6:09

2 Answers 2

4

You are returning old request not cloned one.

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = localStorage.getItem('token');
    request = request.clone({
        setHeaders: {
            Authorization: `Bearer ${token}`
        }
    });

    return next.handle(request);
}
Sign up to request clarification or add additional context in comments.

Comments

2

request.clone() returns an object, doesn't mutate the origin.

try pass request.clone() as parameter.

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {        
        const token=localStorage.getItem('token');
        console.log(token);    
        return next.handle(request.clone({ headers: request.headers.set('Authorization', token) });)
    }

1 Comment

Tried but getting blocked by CORS policy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.