16

I try to set an Authorization header to a GET request to authenticate users to a rest API. I'm using Angular 2 RC1. (I'am a total beginner).

getTest(){
    let authToken = localStorage.getItem('auth_token');
    let headers = new Headers({ 'Content-Type': 'application/json' });
    headers.append('Authorization', `Bearer ${authToken}`);

    let options = new RequestOptions({ headers: headers });
    return this._http
      .get(this._url,options)
      .map(res => console.log(res));
  }

I allow CORS in my backend.

header("Access-Control-Allow-Origin: *");
header("Access-Control-Request-Headers: Content-Type, Authorization");

My console :

OPTIONS api/userProfile/

XMLHttpRequest cannot load /userProfile/. Response for preflight has invalid HTTP status code 406

My request headers

Any idea ?

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Adrien Castagliola
  • 911
  • 2
  • 11
  • 30

2 Answers2

26

I think that you need the Accept header rather because of the 406 status code...

let authToken = localStorage.getItem('auth_token');
let headers = new Headers({ 'Accept': 'application/json' });
headers.append('Authorization', `Bearer ${authToken}`);

let options = new RequestOptions({ headers: headers });
return this._http
  .get(this._url,options)
  .map(res => console.log(res));

This allows you to tell the server which content type you expect in the response...

The Content-Type header is rather to specify the type of the content you sent in the request. In your case, there is no content...

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • I see, it seems that the second header is the problem now. Without it, it works fine but with the Authorization header, it's not working, 406 status code. Any suggestion ? – Adrien Castagliola Jul 04 '16 at 14:20
  • Perhaps you use the `withCredentials` property to `true` within the request options. It's available from RC2... – Thierry Templier Jul 04 '16 at 14:23
1
autorization =  { Authorization: 'Token adfasdfadf651f65asd1f65asdf' }

this.http.get(url, { headers: autorization})
Gregory
  • 6,514
  • 4
  • 28
  • 26