Abhishek Abhishek - 10 months ago 138
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 Source

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 ' +

  getCompanies() {
    var headers = new Headers();

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


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