Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set headers on get request angular 2

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 ?

like image 587
Adrien Castagliola Avatar asked Jul 04 '16 13:07

Adrien Castagliola


People also ask

How do you pass headers in angular HTTP?

There are two ways by which we can add the headers. One, we add the HTTP Headers while making a request. The second way is to use the HTTP interceptor to intercept all the Requests and add the Headers. In both cases, we use the httpHeaders configuration option provided by angular HttpClient to add the headers.

How do I add a header to my HTTP request?

To add custom headers to an HTTP request object, use the AddHeader() method. You can use this method multiple times to add multiple headers. For example: oRequest = RequestBuilder:Build('GET', oURI) :AddHeader('MyCustomHeaderName','MyCustomHeaderValue') :AddHeader('MySecondHeader','MySecondHeaderValue') :Request.

What is HttpHeaders?

In simpler terms, HTTP headers are the code that transfers data between a Web server and a client. HTTP headers are mainly intended for the communication between the server and client in both directions.


1 Answers

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...

like image 71
Thierry Templier Avatar answered Oct 05 '22 01:10

Thierry Templier