title: Angular2: Support for withCredentials and useXDomain
body: <p>I am new to angular2.  I am trying to login to my Django server which is a production server from localhost where i am currently writing my front end code.  Also, I am port forwarding to my production server.
  I keep getting the CORS issue.
  Here is the error i get in my console:</p>
  
  <blockquote>
    <p>XMLHttpRequest cannot load <a href="https://www.smartkart.ca/api/user/login/" rel="nofollow noreferrer">https://www.smartkart.ca/api/user/login/</a>. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '<a href="http://127.0.0.1:8000" rel="nofollow noreferrer">http://127.0.0.1:8000</a>' is therefore not allowed access.</p>
  </blockquote>
  
  <p>I have written my HTTpService and have read almost all the blogs out there to figure out an solution but no luck.  I believe i need to use the withCredentials: true property.  I read some blogs and have modified my code to support withCredentials but no luck.</p>
  
  <p>Here is my code snippet:</p>
  
  <pre><code>import {Injectable} from 'angular2/core';
  import {Http} from 'angular2/http';
  import 'rxjs/add/operator/map';
  import {Headers} from 'angular2/http';
  import {BaseRequestOptions, RequestOptions} from 'angular2/http';
  
  
  @Injectable()
  export class HTTPService {
  constructor(private _http: Http) {
  
  }
  
  baseUrl: String = "https://www.smartkart.ca/";
  getStoreList() {        
      return this._http.get(this.baseUrl + 'api/current/store/')
          .map(res =&gt; res.json());
  };
  
  getCookie(name) {
      let value = "; " + document.cookie;
      let parts = value.split("; " + name + "=");
      if (parts.length == 2) 
      return parts.pop().split(";").shift();
  };
  
  
  login(){  
      // var request = new XMLHttpRequest();
      // var params = JSON.stringify({'email': 'karan@smartkart.ca', 'password': 'k0ttawa#1234'});
      // request.open('POST', this.baseUrl+ "api/user/login/", true);
      // request.onreadystatechange = function() {if (request.readyState==4) alert("It worked!");};
      // request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      // request.setRequestHeader("Content-length", params.length.toString());
      // request.setRequestHeader("Connection", "close");
      // request.send(params);             
      var data = JSON.stringify({'email': 'test@smartkart.ca', 'password': 'blahblah'});     
      var params = data;  
      var headers = new Headers ();
      headers.append('Accept', 'application/json');
      headers.append('Authorization', 'Basic ' + btoa('karan@smartkart.ca:k0ttawa#1234'));
      headers.append("Content-type", "application/x-www-form-urlencoded, application/json");
      // headers.append("Content-length", params.length.toString());
      // headers.append('Access-Control-Allow-Origin', '*');
      // headers.append('Access-Control-Request-Headers', 'x-requested-with');
      // headers.append('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
      // headers.append('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
      // headers.append('Access-Control-Allow-Credentials', 'true');
      // headers.append('Content-Type', 'pplication/x-www-form-urlencoded');
      // headers.append('X-CSRFToken', this.getCookie('csrftoken'));
  
      return this._http.post(this.baseUrl+ "api/user/login/", params,
           {
               headers: headers
           }
      ).map(res =&gt; res.json())
  
  };
  
  }
  </code></pre>
  
  <p>here is what i see in my network tab in the browser</p>
  
  <p><a href="https://i.stack.imgur.com/6JZIa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6JZIa.png" alt="enter image description here"></a></p>
  
  <p>Now if i take away the authorization header i do get logged in and i get back the csrf token but i can never get any response from the server due to the CORS issue.  Here is a snapshot</p>
  
  <p><a href="https://i.stack.imgur.com/4Fx8R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4Fx8R.png" alt="enter image description here"></a></p>
  
  <p>I read some blogs where there were workarounds.  I tried that too but no success.</p>
  
  <p>Here is my code for the workaround:</p>
  
  <pre><code>import {Injectable} from 'angular2/core';
  import {BrowserXhr } from 'angular2/http';
  
  @Injectable()
  export class CORSBrowserXHr extends BrowserXhr {
  
  build(): any {
      let xhr = super.build();
      xhr.withCredentials = true;
      return &lt;any&gt;(xhr);
  }
  }
  </code></pre>
  
  <p>And in bootstrap i add the following:</p>
  
  <pre><code>/// &lt;reference path="../typings/browser.d.ts" /&gt;
  import {bootstrap} from 'angular2/platform/browser';
  import {AppComponent} from "./app.component";
  import {ROUTER_PROVIDERS} from "angular2/router";
  import {APP_BASE_HREF} from 'angular2/router';
  import {provide} from 'angular2/core';
  import {LocationStrategy, HashLocationStrategy} from 'angular2/router';
  import {HTTP_PROVIDERS} from "angular2/http";
  import {BrowserXhr} from 'angular2/http';
  import {CORSBrowserXHr} from "./CORSBrowserXHr.services";
  
  bootstrap(AppComponent, [ROUTER_PROVIDERS, HTTP_PROVIDERS,       provide(BrowserXhr, {useClass:CORSBrowserXHr}),
  provide(LocationStrategy, {useClass: HashLocationStrategy})]);
  </code></pre>
  
  <p>I understand angular2 is under beta but i believe that by now they must have comeup with a solution for CORS support.  If someone has any ideas please comment.</p>
  
  <p>Thanks in advance!!</p>