I have developed a mobile app using phonegap 3.5 and implemented a CORS request in the following manner:
function createCORSRequest(method, url, asynchronous) {
var xhr = new XMLHttpRequest();
//var n = currentTime.getTime();
var n = 'nocache=' + generateRandomString(10);
if (url.indexOf('?') == -1) {
n = '?' + n;
}
else {
n = '&' + n;
}
if ("withCredentials" in xhr) {
xhr.open(method, url + n, asynchronous);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
Then, I proceed to create a request object:
var url = base_url + 'login.php';
var xhrLogin = createCORSRequest('POST', url, false);
var formData = new FormData();
formData.append('loginemail','<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="345574561a575b59">[email protected]</a>');
formData.append('pwd','mypassword');
xhrLogin.send(formData);
On the server side, the PHP code looks like this:
$postdata = '';
foreach($_POST as $key => $value)
{
$postdata .= ' ' . $key . '=' . $value . ';';
}
if (strlen($postdata) == 0) {
sendResponse(200, 'Error: No post data ' . $postdata, 'text/html');
return;
}
When testing this code directly from a browser, it functions properly regardless of the base_url configuration. However, when running it through the phonegap server, issues arise with posting data to the production server while working fine with a test server. Network monitoring indicates the data is being sent in both cases.
The behavior is different on Android/iOS devices compared to running on the phonegap server or pointing to the production server. Could it be related to PHP versions?
Update: Testing from home resulted in successful communication with both servers, suggesting a potential proxy issue.
Update2: Using a Mac for phonegap serve resolved the problem, hinting at possible OS-related considerations.
Notably, the version discrepancy between installations – 3.5.0-0.21.14 at work and 3.5.0-0.20.4 at home – seems to impact functionality. Installing the earlier version at work fixed the issue.
Interestingly, CORS requests function correctly in a Ripple Emulator when disabling the cross domain proxy feature.
To resolve similar problems:
$ npm install -g <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc8c949392999b9d8cbccfd2c9d2ccd1ccd2ceccd2c8">[email protected]</a>