imin
imin

Reputation: 4578

headers.set doesn't set the Authorization header

Below is the snippet of code taken from this tutorial but since I'm using Angular 5, I changed headers.append to headers.set.

However, I will still receive 401 Unauthorized error which basically says that I'm unable to authorize my login using JWT. I tried sending the received token using POSTMAN and setting Authorization header without any problem, but my server will always reject my code below.

getTodos(){

    return new Promise((resolve, reject) => {

      let headers = new HttpHeaders();
      headers.set('Authorization', this.authService.token);

      this.http.get('http://localhost:8080/api/todos', {headers: headers})
        .subscribe(data => {
          console.log("ok getTodos");
          resolve(data);
        }, (err) => {
          console.log("NO getTodos");
          console.log("err",err);
          reject(err);
        });
    });
  }

Upvotes: 1

Views: 484

Answers (1)

DrNio
DrNio

Reputation: 1976

Immutable set of Http headers, with lazy parsing. https://angular.io/api/common/http/HttpHeaders

try this

import { HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'my-auth-token'
  })
};

The .set will return the HttpHeaders httpOptions.headers = httpOptions.headers.set('Authorization', 'my-new-auth-token');

In your snippet the result from .set call is not stored anywhere.

Edit: If you need further assistance or explanation what is immutable let me know. Useful URL https://angular.io/guide/http#update-headers - it's always good to check the official documentation.

Upvotes: 2

Related Questions