0

I have made some node.js app which when I go to server/getjson returns a JSON file I produce in my node.js app. Now I want go to server/getjson from my webpage's javascript and retrieve that JSON file and show it in my HTML, but I can't , I'm getting:

XMLHttpRequest cannot load http://localhost:8001/getjson. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

I read a lot of articles about JSONP, CORS etc. but can't seem to solve my problem.

What should I add to my node.js/ client js to make this work?

This is my node.js part of code which works OK when I go manually to server/getjson, but not when called from my javascript on webpage using AJAX.

http.createServer(function(request, response){
var path = url.parse(request.url).pathname;
if(path=="/getjson"){

    var string = JSON.stringify({
        cars: carsArray
    });

    response.writeHead(200, {"Content-Type": "application/json"});
    response.end(string);

}
}).listen(port);

My AJAX part of code is:

   var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
         if (xhttp.readyState == 4 && xhttp.status == 200) {
                document.getElementById("demo").innerHTML = xhttp.responseText;
        }
      };
   xhttp.open("GET", "http://localhost:8001/getjson", true);
   xhttp.send();
kecman
  • 801
  • 12
  • 28
  • Are you using JavaScript in an HTML page loaded from a local file? If so, that's the problem. Your Node code can respond with [CORS headers.](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS) – Pointy Dec 17 '15 at 19:54
  • I finally managed to fix this using this http://stackoverflow.com/questions/5373987/how-to-use-jquery-ajax-calls-with-node-js I was trying for few hours but probably some ' or \ was missing from my response string. – kecman Dec 17 '15 at 20:02

0 Answers0