Reputation: 347
I have an android/iOS app made with Capacitor that serve a html file that make XHR request to my server.
It works fine on iOS emulator/device, but not on android emulator. I get the following error
File: http://example.com/ - Line 0 - Msg: Access to XMLHttpRequest at 'https://example.com/api/users/me?_=1644242401129' from origin 'http://example.com' 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.
I do have an Access-Control-Allow-Origin
set. Proof is that it works on iOS with the following origin allowed :
capacitor://example.com
But on android, it looks like the origin used is http://example.com
as the errors says.
I did allow this url on my headers 'Access-Control-Allow-Origin' but it still fail and get me the same error.
$allowed_domains = [
'https://example.com',
'http://example.com',
'capacitor://example.com', //iOS working fine
];
if (in_array($_SERVER['HTTP_ORIGIN'], $allowed_domains)) {
header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Credentials: true');
}
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: origin, content-type, accept, API');
header('content-type: application/json; charset=utf-8');
http_response_code(200);
exit;
}
Upvotes: 0
Views: 1945
Reputation: 347
Solved it by removing the following entry in capacitor.config.json
"server": {
"hostname": "example.com"
},
This changed my origin to http://localhost
for android and to capacitor://localhost
for iOS.
Allowed both origins on my server and now it works on android but not on iOS. Cookies are not sent with my XHR requests anymore on iOS (working fine on android).
So i guess the solution is to build on iOS with the server hostname, and build on android without it. Great..
Upvotes: 1