Tavish Aggarwal
Tavish Aggarwal

Reputation: 1060

Angular 2 get request with headers

I have come across couple of posts, and I found that we can set headers in get request using code below:

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

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

But in my API if I am doing console.log(req.headers.authorization) I am getting undefined. Please let me know what I am missing here.

Updates:

const headers = new HttpHeaders()
            .set("X-CustomHeader", "custom header value");
console.log(headers); 
this.users = this.http
    .get(
        "https://reqres.in/api/users",
        {headers})
    .do(console.log)
    .map(data => console.log(data));

In code above I am getting headers as shown below: HTTP Headers And on Web API I am getting header as: 'access-control-request-headers': 'authorization'. Issue is I am not getting value of authorization token that I am passing.

Upvotes: 0

Views: 1290

Answers (2)

Rahul Singh
Rahul Singh

Reputation: 19622

Try the following

const headers = new HttpHeaders()
            .set("X-CustomHeader", "custom header value")
            .set("XX","VALUE");

Notice that we are building the HttpHeaders object by chaining successive set() methods. This is because HttpHeaders is immutable, and its API methods do not cause object mutation. Instead, a call to set will return a new HttpHeaders object containing the new value properties.

Update

const headers = new HttpHeaders()
            .set("X-CustomHeader", "custom header value");

this.users = this.http
    .get(
        "https://reqres.in/api/users",
        {headers})
    .do(console.log)
    .map(data => console.log(data));

For more info you can check this link

Upvotes: 1

vegazz
vegazz

Reputation: 1441

If you want headers from your server api you need to add observe to your angular http request. Angular 5 examples:

const options = { observe: 'response' };
this.http.get<ResultResponse>(serverApiUrl, options)
  .pipe(
    map((res: HttpResponse) => {
      console.log(res.headers);
      console.log(res.headers.get('Content-Disposition'));
      return res;
    })
  );

If you want to add (multiple) headers to your angular http request:

const headers = new HttpHeaders()
  .set('Content-Type', 'application/json')
  .set('Authorization', 'Basic ' + btoa(username + ':' + password));
const options = { headers };
return this.http.get<any>('/service/login', options)
  .pipe(
    catchError(this.handleError)
  );

Upvotes: 1

Related Questions