无法传递JSON对象,因为xmlhttp.status === 0

时间:2015-07-13 17:03:03

标签: javascript json node.js

在将此标记为重复之前,请理解我在发布此问题之前已经完成了所有可能的解决方案。我的代码如下:

server.js

var http = require('http');


var foo = function (response) {
    response.writeHead(200, {"Content-Type": "application/json"});
    var otherArray = ["item1", "item2"];
    var otherObject = {
        item1: "item1val",
        item2: "item2val"
    };
    var json = JSON.stringify({
        anObject: otherObject,
        anArray: otherArray,
        another: "item"
    });
    response.end(json);
    // console.log(json + ' was sent');
};

http.createServer(function (request, response) {
    foo(response);
}).listen(8080);

client.js

var server = function() {
    var obj = {};
    xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState === 4) {
            if(xmlhttp.status === 200) {
                obj = JSON.parse(xmlhttp.responseText);
            } else {
                alert('readyState === 4 but status === ' + xmlhttp.status);
            }
        } 
    };
    xmlhttp.open("GET", "http://localhost:8080", true);

    xmlhttp.send();
};

server();

我正在尝试将JSON对象从服务器传递到客户端。我用我的服务器运行     node server.js 然后我打开我的index.html来源client.js。 使用console.log,我发现我的server.js运行正常,client.js确实影响了index.html。但是,当我尝试执行上面的代码片段时,我在obj中得到一个空对象。 stackOverflow上的一些答案建议将FireFox中的security.fileuri.strict_origin_policy值设置为false,这是我已经完成的,但我仍然得到status === 0

1 个答案:

答案 0 :(得分:0)

听起来您遇到了跨域问题,因为index.html文件未由server.js提供,因此被视为本地文件。当您转到server.js的根路径时,请尝试index.html显示localhost:8080

有关提供简单静态网络文件的信息,请参阅Using node.js as a simple web server。您可能还需要查看http://expressjs.com/,因为它处理了Web服务器应该执行的许多基本操作。

对于firefox设置security.fileuri.strict_origin_policy,它在我看来这样只允许你引用本地文件中的静态本地文件而不是发出ajax请求。