No 'Access-Control-Allow-Origin' header is present on the requested resource Ionic

I am trying to get my Ionic app to authenticate user with ASP.NET Web Api hosted on my development PC. Here is what I’m getting in console:

XMLHttpRequest cannot load http://localhost:50669/token. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 400.

Here is my login function:

login(data){
    data.grant_type = 'password';
    return this.http.post(this.baseUrl+'token', data)
    .map(this.extractData);
  }

  private extractData(res: Response){
    let body = res.json();
    if (body.access_token != null){
      window.localStorage.setItem('token', body.access_token);
    };
    return body || {};
  }

I’ve checked https://www.html5rocks.com/en/tutorials/cors/ and other ionic v1 forum questions/answers - couldn’t help me much. I’ve also tried to add google chrome extension to enable Cors with the request but that gives this error in console:

response for preflight has invalid HTTP status code 400

I am new to Ionic and need your help to figure out how I can fix this. Also in my ASP app, Access-Control-Allow-Origin has * value and if I use Postman app, everything works fine. I think I need to change the header of the ionic login post request with appropriate header value. Guys, please give me some light on this. Thanks in advance.

1 Like

I have the exact same issue, I passed header with the HTTP get request, it can not get authenticated.

It’s not the headers that you pass to the API, it’s the headers they pass back. You need to configure your API server to send the header

Access-Control-Allow-Origin: *

at least for the OPTIONS request

I got it temporarily resolved… make sure you check with the server side, enables the right ports…

Hello,
how do we fix this problem?
we have to write
this line of code --> Access-Control-Allow-Origin: *
somewhere?
thank you

this is my Error:

Updated **

i installed a plugin in Chrome
so i loaded my url correct
Although i am still having the second Error named HtmlErrorResponse
How can i resolve this?and finally get my console.log from the webservice?

Try this chrome extension plugin
CORS extension

1 Like

i am also getting same error … how to resolve this??

You can solve this error in 2 ways that I will mention below:
1.- Install an extension for chrome called “CORS” which will allow you to make requests and send tokens.

2.- Configure on the server side the section of “Access-Control-Allow-Origin: *” that allows you to send data in the headers of authorization “Header”

2 Likes