1

我在 node.js 中编写了一个 HTTP 服务器

var http = require('http');
http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World ' + request.url + '\n\n');
  console.log(request.url);
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');

这应该满足来自 phonegap / cordova 应用程序的请求:

function testnodejs() {
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)  {
        alert ("Your webbrowser does not support HTTP Request");
        return;
    }
    var url="http://domain.com:8124/i.t?hi=hi!";
    console.log(url);
    document.getElementById("maindiv").innerHTML = "<div id='itembrd' onClick=\"testnodejs();\"><div id='item'>Nodetest</div></div>";
    xmlHttp.open("GET", url, true)
xmlHttp.onreadystatechange=function() {
        document.getElementById("maindiv").innerHTML += xmlHttp.status + " ";
        if (xmlHttp.readyState==4) {
            console.log(xmlHttp.responseText);
            document.getElementById("maindiv").innerHTML += xmlHttp.responseText + '<br />\n';
        }
    }
    xmlHttp.send(null)
}

在 config.xml 我有

<access origin=".*" />

该请求返回一个 readyState 4,但当您期望 200 时返回一个状态 0。有人知道吗?

4

1 回答 1

3

So, I put this aside for a couple of days. Headed back in with fresh abandon and fixed it. The issue was at the node.js server side which doesn't return 200 but 0. That's because of allow origin. I rewrote the response header thusly:

response.writeHead(200, {
    'Content-Type': 'text/plain',
    'Access-Control-Allow-Origin' : '*'
});

and voila! tango!

Now I have a very lightweight solution for XHR requests from within cordova / phonegap apps.

于 2012-09-03T08:39:52.920 回答