Home > Software engineering >  Angular headers.get(...) is null
Angular headers.get(...) is null

Time:11-26

I'm building an angular 14 application with a backend using spring cloud gateway. I have configured CORS in the gateway. I run the application on http://localhost:4200. The first call to the backend is to get user information. I defined a method :

getUserInfo() {
    const httpOptions = {
      headers: new HttpHeaders({
          'Access-Control-Allow-Origin':'*',
          'Content-Type':  'application/json'
      })
    };
    return this.http.post<any>("http://localhost:8180/auth/userInfo", {}, httpOptions)
        .pipe(map(user => {
            // store user details in local storage to keep user logged in between page refreshes
            localStorage.setItem('currentUser', JSON.stringify(user));
            this.currentUserSubject.next(user);
            return user;
        }));
}

And I have 2 Interceptors : 1 for setting the X-Requested-With header and 1 for intercepting errors :

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(catchError(err => {
    
        if (err.error instanceof ErrorEvent) {
            // A client-side or network error occurred. Handle it accordingly.
            console.error('An error occurred:', err.error.message);
            
            const error = err.error.message;
            return throwError(error);
         } else {
             console.error(`Error type ${err.name}`);
             console.error(err.message);
            // The backend returned an unsuccessful response code.
            // The response body may contain clues as to what went wrong,
            if (err.status === 401) {
                console.warn(`Backend returned code 401, login out`);
                // auto logout if 401 response returned from api
                this.authenticationService.logout();
                this.router.navigate(['/login']);
            } else {
                console.error(`Backend returned code ${err.status}`);
                if (err.error) {
                    console.error(`app error code was: ${err.error.code}`);
                }
            }
              
            return throwError(err);
          }
    }))
}

The problem I get is the call to getUserInfo() always return a TypeError error with the message "headers.get(...) is null"

I can't see any request made to the backend neither in my browser log or in the backend access log.

Do you have any idea? Thanks

EDIT

The call to the getUserInfo() is in a component :

ngOnInit() {
    //this.loading = true;
    this.authenticationService.getUserInfo()
        .pipe(first())
        .subscribe(
            data => {
                this.router.navigate(['/']);
            },
            error => {
                this.errorMsg = error.message;
            });
}

CodePudding user response:

  • Verify that you Import HttpHeaders from @angular/common/http.
  • Try to use the tap to console the data before the map
  • In your components verify that you subscribe to getserInfo function.

In the Service try to use that in the ctor

constructor(){
this.header=new HttpHeaders();
this.header=this.header.append('ContentType','application/json');
this.header=this.header.append('Accept','application/json')
}

and call it

//code...
  return this.http.post(url,{},{headers:this.header});

CodePudding user response:

My bad, it was due to an another interceptor that I put to work with a mock configuration and that was causing the error.

  • Related