Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 7 not sending correct header on request

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!

like image 883
Augusto Avatar asked Nov 08 '18 01:11

Augusto


2 Answers

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 !!

like image 141
Rahul Avatar answered Nov 15 '22 05:11

Rahul


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

like image 34
Augusto Avatar answered Nov 15 '22 05:11

Augusto