Angular 7 not sending correct header on request

10,612

Solution 1

I was able to solve this problem by creating an interceptor:

import { Injectable } from '@angular/core';
    import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
    import { Observable } from 'rxjs';

    import { AuthenticationService } from '../_services/authentication.service';

    @Injectable()
    export class JwtInterceptor implements HttpInterceptor {
      constructor(private authenticationService: AuthenticationService) {}

      intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // add authorization header with jwt token if available
        let currentUser = this.authenticationService.currentUserValue;
        if (currentUser && currentUser.token) {
          request = request.clone({
            setHeaders: {
              Authorization: `${currentUser.token}`
            }
          });
        }

        return next.handle(request);
      }
    }

Thanks

Solution 2

Everything seems to be correct for me - but i have some small changes in your code

Don't bind HttpOptions directly bind the HttpHeaders in the request check the below code

getAll() {

const httpHeaders = new HttpHeaders ({
     'Content-Type': 'application/json',
     'Authorization': 'Bearer validToke.' 
   });

return this.http.get<user[]>(`http://localhost:3000/api/users`, { headers: httpHeaders });
}

Now this will add your headers for the request - if you are using to get data from different domain - try to add cors on your server - the browser will pre-flight the request as HttpOptions and then bind it as HttpGet in your case

Hope it works - happy coding !!

Share:
10,612
Admin
Author by

Admin

Updated on June 22, 2022

Comments

  • Admin
    Admin almost 2 years

    I can not send the correct headings in angular 7! I use passport on my backend:

    "app.get('/api/users', passport.authenticate('jwt', {session: false}), (req, res, next) => {... bla bla bla...}."
    

    When I try send a valid token from postman to my path / api / users everything works correctly, but when i do it from angular not. (*Angular dont show error!) Suppose 'Bearer validToken' is a valid token In this way i send the headers:

    getAll() {
    
    const httpOptions = {
    headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'Authorization': 'Bearer validToke.' 
      });
    };
    
    return this.http.get<user[]>(`http://localhost:3000/api/users`, httpOptions);
    }
    

    I can authenticate from angular and get the Bearer token, everything works correctly, I can get the list of users if I remove passport.authenticate ('jwt', {session: false})

    Thank you for reading!