Search code examples
angularangular-httpclient

how to add JWT in angular 6


I have added the authorization key as the given below

postrequest(callurl, input) {
const headers: any = new Headers;
headers.append('Content-type', 'application/json;charset=utf-8');
headers.append('Authorization', 'Bearer 
  '+localStorage.getItem("AuthTocken"));
return this._http.post(callurl, input, headers)
  .pipe(
    map((res: any) => {

      return res;
    }),
    retry(2),
    catchError(err => {
  })
 );
}

i didnt fount any error but the Authorisation is not found in the header

angular 6

service used from @angular/common/http

URL working fine in postman

i get the error as follows

http.service.ts:84 Backend returned code 0, body was: [object ProgressEvent] body was: {"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":null,"ok":false,"name":"HttpErrorResponse","message":"Http failure response for (unknown url): 0 Unknown Error","error":{"isTrusted":true}} (anonymous) @ http.service.ts:84 push../node_modules/rxjs/_esm5/internal/operators/catchError.js.CatchSubscriber.error @ catchError.js:34

Responce Headers enter image description here


Solution

  • you must use Bearer instead of Token

    headers.append('Authorisation', 'Bearer '+'localStorage.getItem("AuthTocken"));
    

    header object is an option. you must pass header as argument in below form

    this.http.post(url, data, { headers: headers })