I am working with ajax and node js for the first time. When I use the client to get response from node js it gets into the error function. On the other hand, when I directly call the url from the browser, I get the correct response from the server. This is an indication that something is wrong with the client side ajax request.
This is my client code :
function fetch() {
$.ajax({
type: 'POST',
url: "http://127.0.0.1:8888",
data: {data : 'India'},
dataType: 'json',
success: function () {
alert("hi");
//var ret = jQuery.parseJSON(data);
//$('#q').html(ret.msg);
},
error: function (jqXHR, textStatus, error) {
console.log('Error: ' + error.message);
alert("ERROR");
}
});
This is the server node.js code (part of it). The console.log msg get the correct values.
http.createServer(function(req, response) {
console.log("Request received");
response.writeHeader(200, {"Content-Type": "application/json"});
req.on('data', function (chunk) {
console.log(chunk.toString('utf8'));
console.log(result[0].name);
});
response.end(JSON.stringify({data:result}));
}).listen(8888);
All the console.log in the server gets the correct values. That means the response is not reaching back when there is ajax request, but on directly writing 127.0.0.1:8888, I get correct response.
The message on the console is :
XMLHttpRequest cannot load http://127.0.0.1:8888/. Origin null is not allowed by Access-Control-Allow-Origin.
Please someone help to fix this out. I have been on this for a day now.
EDIT : Screen capture of the network tab. As you can see the server gets the request but the client does not get the response. This is done even after writing 'Access-Control-Allow-Origin' : '*'.