Home > Mobile >  JWT not being send on post request 401 error Angular and NodeJS
JWT not being send on post request 401 error Angular and NodeJS

Time:02-23

I am making a MEAN stack with JWT and my backend with nodeJS work perfectly with postman, now when I try sending a post request then I get a 401 saying (from backend) that I am missing the token, which i am storing on the localstorage. Maybe my approximation of storing the token on the localstorage is wrong? Here is my code by files:

AuthService.ts

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  endpoint: String='http://localhost:8080/api';
  userToken: String;

  constructor(private http:HttpClient) {
    this.readToken();
   }

  logout(){

  }

  login(usuario: Usuario){
    const authData= {
      ...usuario
    }

    return this.http.post(`${this.endpoint}/auth/login`, authData)
      .pipe(map(resp =>{
        this.guardarToken(resp ['token'])
        return resp;
      })
      )
  }

  nuevoUser(usuario: Usuario){
    const authData= {
    ...usuario
  }

  return this.http.post(`${this.endpoint}/usuarios`, authData)
  .pipe(map( resp =>{
    this.guardarToken(resp['token'])
    return resp;
    })
    )
  }

  private guardarToken(xtoken:string){

    this.userToken = xtoken;
    localStorage.setItem('token',xtoken);
    //return JSON.parse(localStorage.getItem('token')|| '{}');

  }

  
  readToken(){
    
    if(localStorage.getItem('token') ){
      this.userToken = localStorage.getItem('token');
    }else{
      this.userToken = '';
    }

    return this.userToken
 
  }

}

ApiService.ts

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  apiToken = localStorage.getItem('token');
  //apiToken = this.auth.readToken();
  endpoint: string = 'http://localhost:8080/api';
  headers = new HttpHeaders().set('Content-Type', 'application/json')
                              .set('Authorization', `token ${this.apiToken}`); 

  

  constructor(private http:HttpClient, private auth:AuthService) { }

   // Add 
   AddCliente(cliente: Cliente): Observable<any> {
    let API_URL = `${this.endpoint}/clientes`;
    return this.http.post(API_URL, cliente, { headers: this.headers })
      .pipe(
        map((resp: any)=>{
          cliente._id = resp.nombre;
          return cliente;
        }),
        catchError(this.errorMgmt)
      )
  }
}
//more crud stuff

interceptors

@Injectable()
export class HttpConfigInterceptor implements HttpInterceptor {
    constructor(
        private router: Router,
        private auth: AuthService
      ) {}
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        console.log("Interception In Progress");  
        //const token: string = localStorage.getItem('token');
        const token = this.auth.readToken(); 
        request = request.clone({ headers: request.headers.set('Authorization', 'token '   token) });  
        request = request.clone({ headers: request.headers.set('Content-Type', 'application/json') });  
        return next.handle(request)  
        .pipe(  
           catchError((error: HttpErrorResponse) => {  
                 
                if (error && error.status === 401) {  
                    console.log("ERROR 401 UNAUTHORIZED")  
                }  
                return throwError(()=>error);                      
           })  
        );  
  }
}

Edit: adding image of the headers

headers description

CodePudding user response:

maybe you forget to put in app.module this:

  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: TokenInterceptor ,
    multi: true,
  }..

CodePudding user response:

After reviewing my code, front and back, i try adding the authorization in a separate line in my nodejs server as following:

res.setHeader("Authorization","Bearer");  

then everything start to work as suppose, thanks all for your time.

  • Related