Problem with CORS and ionic serve

I am trying to test my app against a REST server created with .NET Core 2.2, but when I try to access the server I am getting this error:

Access to XMLHttpRequest at 'http://localhost:5000/sessions' from origin
'http://localhost:8100' has been blocked by CORS policy: Response to preflight request 
doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present
on the requested resource.

The thing is that I am sure my server is configured to allow all origins, because I can access that server from other computers on the network. I’ve reading a lot about CORS problems with Ionic, and it seems that if the server is allowing all origins, the ionic app shouldn’t have problems accesing it.

BTW, I am testing the server access with ionic serve.

TIA

If you really not bothered about just to work with in dev environment you can just use an this extension and it will allow using ionic serve without CORS issue.

And if you don’t want to use plugin in your config.xml add <access origin="*" />

Thanks for your answer. My config.xml already has <access origin="*"> . I also tried the pluging you suggested, but problem remains. I also followed this post, but it seems ionic serve refuse to use the proxy configuration, either via angular.json or using the —proxy-conf setting.

I also tried with ionic cordova run browser, but problems remains the same. :frowning: . Its really frustrating and its hitting my time schedule :frowning:

Just tried with this post and still seems that the proxy configuration is just not being applied. :frowning:

Well, it turned out the problem was being caused by a header I was sending on. I just discovered that if you send the Content-Type: application/json header, the CORS error is triggered; if I remove it, then everything works fine. I’ll be damed! two days lost because of this :(.

I spoke too quickly, Angular adds a Content-Type: application/json automatically when sending a POST request, so I am back with the CORS error :frowning: . Just GET requests are working now.

Im having the same problem using ionic studio
GET works, POST doesn’t…
tried all the mentioned solutions, nothing worked

But it’s absurd. I am sure many people has created apps with Ionic that works against web servers. The solution has to be somewhere.

Is this on android ?

we are running into this with chrome 76b https://bugs.chromium.org/p/chromium/issues/detail?id=991107

Right now I dealing with the problem on browser (ionic serve). I just remembered a similar situation I faced a couple of years ago with a WebConnection project and found a way to bypass the CORS problem with POST + JSON: using form-url-encoded.

In my case, the webserver was created with .NET Core 2.2, so I modified my endpoint to indicate that the data would arrive in x-www-form-urlencoded:

// POST /session
// { loginid: string, password: string }
//
// Iniciar una sesion de usuario.
//
[HttpPost]
[Consumes("application/x-www-form-urlencoded")]
public IActionResult postSessions([FromForm] postSessionsRequest data)
{...}

Lucky me, I have my own rest service to wrap all rest operations, so I created a new postForm method like this:

postForm(url: any, data?: any): Promise<any> {
    let options = {
      headers: new HttpHeaders({
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded'        
      })
    };    
    data = data || {};
    let formData = this.delegate.objectToFormData(data);
    return this.delegate.post(url, formData, options);
  }

The objectToFormData takes an object like { token1: "value1". token2: value2 } and converts it to token1=value1&token2=value2. Then, that string is sent as the post request’s data, and his way I avoid sending a post with application/json content and avoid CORS to get in the middle.

Unfortunatelly, same trick can’t be applied to get DELETE methods to work over CORS, so I am chaning my DELETE resource/:id routes to POST resource/:id/delete, at leat until I found a way to make all verbs to work over CORS.

hi vespinasgmailcom
First you have to return the response of service in JSON because error shows that you are sending response in xml as I have faced same issue then you have to test your app on real device and use native http plugin for calling this api as

ionic cordova plugin add cordova-plugin-advanced-http
npm install @ionic-native/http

constructor(
private nativeHttp: HTTP,
) {

from(this.nativeHttp.get(ApiService.MAINDOMAIN+“Employee/Get?employeeID=”+EmployeeID,{},{}))
.subscribe(data => {
console.log(data.data,“it is original”,data);
resolve(data.data);
}, err => { console.log('Native Call api.getemployee error: ', err);reject(err); });

}

it will solve your problem
cheers!!

Yes… in the device. My problem is that testing on the device is a time consuming task, so I use to test as most as I can in browser, and there is where I having this annoying problem.

First you have to return the response of service in JSON

All my endpoints returns JSON data.

bro native http plugin does not work on browser so you have to have test it on device if you want to resolve your problem and save your searching time for problem solve.

cheers!!

Yeah, you are probably right… but I am a little stubborn :slight_smile:

If you are using ionic native’s http replace with angular/http.

  1. Add HttpClientModule to app.module.ts
  2. Use HTTP in constructor eg; private http: Http,
  3. Import from @angular/http ex: import { Http} from ‘@angular/http’;
    If you are handling CORS from server side it should work.
    This will work on both ionic serve on browser and device as well.

I just fixed it on my end… post and get works now using HttpClient!
All I did is to configure my backend (swift in my case) to allow CORS to the localhost.

Well what if I’m developing a PWA and run into cors error? Can’t switch to native http because it doesn’t work in browser and don’t have access to the API to correct the cors problem from server… Now what?

angular/http does work for both browser and devices as well.

Yes, ofcource it does, but how do I fix cors error when useing angular/http if I do not have access to the API server to fix cors error configuring the server? You missed my point in my first question.

Well, there is no way to handle the server side CORS issue at client side.