Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 http.get is not sending the token in the header

I have a post method which is working and fetching my token from the server

authenticate() {
  let url = this.server + 'authenticate';
  let headers = new Headers({ 'Content-Type': 'application/json' });
  let options = new RequestOptions({ headers: headers });

  let body = JSON.stringify({
    'password': 'admin',
    'rememberMe': true,
    'username': 'admin'
  });
  return this._http.post(url, body, options)
    .map((res: Response) => res.json())
    .subscribe(result => this.token = result.id_token);
}

where this.server is a string having the url of the server. and this._http is just an instance of the angular Http

private _http: Http;
constructor(http: Http) {
  this._http = http;
}

and this.token is just an empty string private token: string;

Now all this is working just fine and I am getting the right token from the server. My problem is that when I try to use this token in a get method it doesn't work and I get a 401 (unauthorized) error.

My buggy get method is:

getData(src) {
  let url = this.server + src;
  let headers = new Headers({'Authorization': 'Bearer ' + this.token});
  return this._http.get(url, headers)
  .map((res: Response) => res.json())
  .subscribe(res => console.log('res'));
}
like image 717
Mostafa Fateen Avatar asked Mar 07 '26 19:03

Mostafa Fateen


1 Answers

So the problem was that I should have added {} around the headers when I sent them. the get should be this._http.get(url, { headers })

like image 180
Mostafa Fateen Avatar answered Mar 10 '26 07:03

Mostafa Fateen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!