CORS issue on simulator

Hi,

I am running into CORS issue on Android simulator. I have set ‘Accests-Control-Allow-Origin’ to ‘*’ to enable CORS on my APIs, but am getting the following error:

A wildcard ‘*’ cannot be used in the ‘Access-Control-Allow-Origin’ header when the credentials flag is true. Origin ‘http://localhost’ is therefore not allowed access

I am using {withCredentials: true} in the post method, without this the HTTP session on my server didn’t seem to work.

My environment:

cli packages: (/usr/lib/node_modules)

@ionic/cli-utils  : 1.19.2
ionic (Ionic CLI) : 3.20.0

global packages:

cordova (Cordova CLI) : 8.0.0 

local packages:

@ionic/app-scripts : 3.2.1
Cordova Platforms  : android 7.0.0
Ionic Framework    : ionic-angular 3.9.3

System:

Android SDK Tools : 26.1.1
Node              : v8.14.0
npm               : 6.4.1 
OS                : Linux 4.10

Environment Variables:

ANDROID_HOME : /home/ramashishb/Android/Sdk

Misc:

backend : pro

Any idea whats wrong?

Thanks,
Ramashish

Hi,

I don’t know how you handle requests on your server but I’ll do it like the code below:

Server(*.php file)

function checkCORS() {
	if (isset($_SERVER['HTTP_ORIGIN']) && isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
		header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
		header('Access-Control-Allow-Credentials: true');
		header('Access-Control-Max-Age: 86400');    // cache for 1 day
		header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
		header('Access-Control-Allow-Headers: X-Requested-With, Content-Type, X-API-TOKEN');

		if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') return true;
		else {
			if (isset($_SERVER['HTTP_X_API_TOKEN']) && $_SERVER['HTTP_X_API_TOKEN'] == 'WHATEVERYOUSENDFROMAPP') return true;
			else return false;
		}
	} else return false;
}

And my .ts file sends this:

this.http.post(`${this.serverUrl}`, {uuid: this.device.uuid, model: this.device.model}, {headers: this.headers})
.subscribe(response => {
       console.log(response);
});

private headers = new HttpHeaders({
      'X-API-TOKEN': 'WHATEVERYOUSENDFROMAPP'
});

You don’t have to use the X-API-TOKEN neither on client nor on server.

Hope this helps you.

Cheers

Thank you very much. It helped. I was missing Access-Control-Allow-Credentials header.

Ramashish