Abhishek Abhishek - 1 month ago 20
TypeScript Question

Angular2 http.request not able to add headers

I have this code in Angular2 TypeScript where I am trying to add headers like the following.

['access-token', localStorage.getItem( 'token' )],
['client', localStorage.getItem( 'client' )],
['uid', localStorage.getItem( 'email' )],
['withCredentials', 'true'],
['Accept', 'application/json'],
['Content-Type', 'application/json' ]


While sending the request I can't see the headers in my request.
I am working on a cross domain setup. Is there some other way to do it?

private _request(url: string | Request, options?: RequestOptionsArgs) : Observable<Response> {

let request:any;
let reqOpts = options || {};
let index:any;

if(!reqOpts.headers) {
reqOpts.headers = new Headers();
}

for( index in this._config.authHeaders ) {
reqOpts.headers.set( this._config.authHeaders[index][0], this._config.authHeaders[index][1] );
}

request = this.http.request(url, reqOpts);

return request;
}


This is my response header
enter image description here

Answer

If your request is a cross domain one so CORS concepts apply. You can have a look at these links for more details: http://restlet.com/blog/2015/12/15/understanding-and-using-cors/ and http://restlet.com/blog/2016/09/27/how-to-fix-cors-problems/. Sure, as G√ľnter said, there is something to do on the server side to return the CORS headers to allow your browser to handle the response.

Here is a sample service that adds headers in an HTTP request:

export class MyService { 
  constructor(private http:Http) {
  }

  createAuthorizationHeader(headers:Headers) {
    headers.append('Authorization', 'Basic ' +
      btoa('a20e6aca-ee83-44bc-8033-b41f3078c2b6:c199f9c8-0548-4be7-9655-7ef7d7bf9d33')); 
  }

  getCompanies() {
    var headers = new Headers();
    this.createAuthorizationHeader(headers);

    return this.http.get('https://angular2.apispark.net/v1/companies/', {
      headers: headers
    }).map(res => res.json());
  }

Edit

I just saw that you try to set the withCredential header. I think that you mix different things. withCredentials isn't a standard header but there is a withCredentials property on the XHR JavaScript object. See this link: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials. This should work without using the withCredentials custom header.

As a reminder, if you want to use a custom header, you need to add it on the server side within the Access-Control-Allow-Headers header.

Hope it helps you, Thierry