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