Phonegap FormData未使用CORS发送

时间:2014-09-01 15:45:35

标签: javascript cordova cors

我有一个phonegap应用程序(目前正在使用phonegap 3.5),因此我设置了一个CORS请求:

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) {

        // Check if the XMLHttpRequest object has a "withCredentials" property.
        // "withCredentials" only exists on XMLHTTPRequest2 objects.
        xhr.open(method, url + n, asynchronous);
        //xhr.setRequestHeader("pragma", "no-cache");
        //xhr.setRequestHeader('cache-control', 'no-cache');
    } else if (typeof XDomainRequest != "undefined") {
        // Otherwise, check if XDomainRequest.
        // XDomainRequest only exists in IE, and is IE's way of making CORS requests.
        xhr = new XDomainRequest();
        xhr.open(method, url);
    } else {

        // Otherwise, CORS is not supported by the browser.
        xhr = null;
    }
    return xhr;
}

然后我创建了一个请求对象:

var url = base_url + 'login.php';
var xhrLogin = createCORSRequest('POST', url, false);
var formData = new FormData();
formData.append('loginemail','a@b.com');
formData.append('pwd','mypassword');
xhrLogin.send(formData);

在服务器上,我有以下PHP:

$postdata = '';

foreach($_POST as $key => $value)
{
    $postdata .= ' ' . $key . '=' . $value . ';';
}
if (strlen($postdata) == 0) {
    sendResponse(200, 'Error: No post data ' . $postdata, 'text/html');
    return;
}

当我在浏览器中运行此代码时,直接从磁盘(或从Brackets)运行它,无论我的base_url变量指向什么,它都可以正常工作。如果我通过phonegap服务器(使用phonegap开发者应用程序在浏览器或设备上)运行此表单数据,那么当我定位我的测试服务器时,表单数据会发布,但在生产服务器上,它会报告不存在POST变量。在每种情况下,我都会在chrome(F12)中查看网络选项卡,并验证是否正在发送用户名和密码。

如果我构建应用程序并在Android或iOS上运行,它可以在任一服务器上正常运行。它似乎从phonegap服务器运行错误,当url指向生产服务器时。 (我也在IE中试过,因为createCorsRequest代码略有不同,同样的事情发生了。)

正如你从第一段代码中看到的那样,我已经尝试过这个论坛上其他帖子的nocache技巧,但有类似的错误,但无济于事。

测试服务器正在运行php 5.5.9-1ubuntu4.3 Prod服务器正在运行php 5.4.20

php的版本会影响这个吗?

更新:我在家里尝试了这个并将数据发送到两台服务器,这可能是代理问题。

Update2:从Mac运行phonegap服务似乎运行正常(我在Linux机器上运行)


看起来这是版本,我在工作时安装了3.5.0-0.21.14,在家里安装了3.5.0-0.20.4。当Mac在工作中工作时,我将我的工作笔记本电脑带回家并进行了测试,它也出现了同样的问题。

有趣的是,如果我从Ripple Emulator运行应用程序,只要我禁用Ripple的跨域代理,CORS请求就可以正常工作。

在工作中安装早期版本已修复问题

$ npm install -g phonegap@3.5.0-0.20.4

1 个答案:

答案 0 :(得分:0)

解决方案是为Android版本添加白名单插件。这启用了config.xml

中指定的URL