Mostafa Fateen
Mostafa Fateen

Reputation: 847

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'));
}

Upvotes: 3

Views: 2379

Answers (2)

Keifer Caebe
Keifer Caebe

Reputation: 617

Http.get takes a url string and an optional RequestOptionsArgs as parameters. Wrapping the header in a RequestOptions object should do the trick.

getData(src) {
  let url = this.server + src;
  let headers = new Headers({'Authorization': 'Bearer ' + this.token});
  let options = new RequestOptions({ headers: headers });
  return this._http.get(url, options)
    .map((res: Response) => res.json())
    .subscribe(res => console.log('res'));
}

Upvotes: 1

Mostafa Fateen
Mostafa Fateen

Reputation: 847

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 })

Upvotes: 1

Related Questions