0

Before you mark this as a duplicate, please understand that I have gone through all the solutions possible before posting this question. My code is as follows:

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();

I am trying to pass a JSON object from server to client. I run my server using node server.js And then I open my index.html which sources client.js. Using console.log, I have found that my server.js is functioning fine and my client.js is indeed affecting index.html. However, when I try to do the above snippet of code, I get an empty object in obj. Some answers on stackOverflow have suggested setting that security.fileuri.strict_origin_policy value in FireFox to false which I have done, yet I am still getting status === 0.

Brant Olsen
  • 5,384
  • 5
  • 34
  • 52
waivek
  • 171
  • 1
  • 5

1 Answers1

0

It sounds like you are having a cross domain issue since the index.html file is not being served up by server.js and thus is treated as a local file. Try having server.js show index.html when you go to the root path for localhost:8080.

Refer to Using node.js as a simple web server for serving a simple static web file. You may also want to look into http://expressjs.com/ as it handles a lot of the basic stuff a web server should do.

As for the firefox setting security.fileuri.strict_origin_policy, it looks to me like this will only allow you to reference static local files from your local file not make ajax requests.

Community
  • 1
  • 1
Brant Olsen
  • 5,384
  • 5
  • 34
  • 52