Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I'm starting learning node.js, but I have a little problem. I have an ajax function that call a server listening on port 8001. Afer I open and load a .json file and I want to send back to the page. For what concern the loading, there is no problem, but when I send back to the page, I get this error : on Chrome "POST http: //localhost:8001/ net::ERR_CONNECTION_REFUSED"; on Firefox "...Reason : CORS request failed."

here the code of my simple file .js :

    var http = require('http'),
          fs = require('fs'),
         url = require('url');
    http.createServer(function (request, response) {
        var path = url.parse(request.url).pathname;
        console.log("request recieved");
        var obj;
        fs.readFile('../menu.json', 'utf8', function (err, data) {
            if (err) throw err;
            console.log(data);
            obj = JSON.parse(data);
            console.log(obj);
            response.writeHead(200, { "Content-Type": "application/json" });
            response.end(obj, "utf-8");        
    }).listen(8001);
    console.log("server initialized !!");

How can I make it works? I also read the other topic, but I have not found a solution. Thank you in advance for your time and patience.

Edit : here is the ajax call :

   function testNodeJs() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST", "http://localhost:8001/", true);
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var string = xmlhttp.responseText;
            alert(string);
    xmlhttp.send();
                Sorry but I'm at the beginning; I also read this question, but I'm not using express.js , so how can I solve?
– d3llafr33
                Aug 10, 2015 at 21:05
                You have to respond to the CORS authorization requests, you can build that manually, but most often a framework component is more helpful -- maybe you should be using Express.js
– Soren
                Aug 11, 2015 at 0:26

The server needs to send a Cross-Origin Resource Sharing (CORS) header. For your simple case, it might be enough to do

response.writeHead(200, { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" });

But it looks like there's an NPM module to help you, too https://www.npmjs.com/package/cors

Additional reading on CORS: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

I install the cors module, and apply your solution, but I don't know why it continues not working :( – d3llafr33 Aug 10, 2015 at 21:06

Try this one:

response.writeHead(200, { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" ,"Access-Control-Allow-Methods":"GET, POST","Access-Control-Allow-Headers","X-Requested-With,content-type, Authorization"});

For more details go through this link: https://annasob.wordpress.com/2012/01/11/getting-around-cors-with-node-js/

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.