Home > Software engineering >  How to properly add Headers in Angular?
How to properly add Headers in Angular?

Time:04-20

Here is the service code in Angular:

getcareer(dataout:any){
   let headers = new HttpHeaders().append('Content-Type', 'application/json').append('Authorization','Bearer' ' ' GlobalService.authtoken);
  //headers = headers.append('Content-Type', 'application/json').append('Authorization','Bearer' ' ' GlobalService.authtoken);
  //let headers={'Authorization':'Bearer' ' ' GlobalService.authtoken}
  console.log(headers);
  return this.http.post('http://localhost:3000/employee/getcareer',
  {'headers': headers })
  .subscribe(data => {
    dataout = data});
}

Now after logging in and trying to access this page, it says 401, Unauthorized. In the browser console, The headers are added in the LazyUpdate section instead of the headers section. I have tried .set .append and some other methods but no luck. Please have a look, thankyou.

Edit: Here is a detailed console in browser (I have printed the httpheaders here in console log):

https://ibb.co/f002tZ9

Above is the link to the image (sorry there is an issue posting an image here). You can see the Headers are not present in 'header' section but in 'lazyupdate' section.

CodePudding user response:

try it like this:

const options = {
  headers: {
    'content-type': 'application/json',
    Authorization: 'Bearer '   GlobalService.authtoken
  }
};

this.http.post('http://localhost:3000/employee/getcareer', options)

CodePudding user response:

As you can see from the POST doc the second param is the data:

/** POST: add a new hero to the database */
addHero(hero: Hero): Observable<Hero> {
  return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
    .pipe(
      catchError(this.handleError('addHero', hero))
    );
}

So in your case, you have to:

  getcareer(dataout:any){
    const headers = new HttpHeaders().append('Content-Type', 'application/json').append('Authorization','Bearer' ' ' GlobalService.authtoken);
    console.log(headers);
    return this.http.post('http://localhost:3000/employee/getcareer',
    null,
    {headers }) //unncessary key-value
    .subscribe(data => dataout = data);
}

  • Related