1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Angular token interceptor does not inject the token [duplicate]

Discussão em 'Angular' iniciado por Nht_e0, Outubro 16, 2024.

  1. Nht_e0

    Nht_e0 Guest

    I have an Angular app that sends a request with a token to a Django server. I am using a token interceptor to inject the token to the requests header:

    @Injectable({
    providedIn: 'root'
    })
    export class TokenInterceptorService implements HttpInterceptor {

    constructor(private account_service: UserRegisterService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = this.account_service.GetToken();
    alert("In the token interceptor");
    console.log("In the token interceptor");
    // Clone the request and add the Authorization header.
    if (token) {
    const tokenized_req = req.clone({
    headers: req.headers.set('Authorization', `token ${token}`)
    });
    console.log("QQQQQQQQQ" + req);
    return next.handle(tokenized_req);
    }
    console.log("PPPPPP" + req);
    return next.handle(req);
    }
    }


    I have updated the app.module.ts accordingly:

    providers: [
    provideHttpClient(withFetch()),
    EventsService,
    {
    provide: HTTP_INTERCEPTORS,
    useClass: TokenInterceptorService,
    multi: true,
    },
    ],


    However, when I check the request header in the server, the token is absent.

    I tested the server separately using Postman and it works fine (i.e., it reads the token and sends the correct data).

    Moreover, none of the alerts or the log messages that I have included in the interceptor are printed. So, I think it never gets called.

    What am I missing here?

    Continue reading...

Compartilhe esta Página