0

I have created an ajax request to localhost whenever a button on my page is pressed. And I have created a server using nodejs listening on port 8080. But when I press the button, following error is given in chrome developer tools terminal:

Access to XMLHttpRequest at 'http://localhost:8080/' from origin 'null' 
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header 
is present on the requested resource.

I am trying to learn how to communicate with the server. I am very new to this so sorry if my questions sounds ridiculous.

Code to make the http request:

function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("print_here").innerHTML = this.responseText;
    }
  };
  xhttp.open("POST", "http://localhost:8080", true);
  xhttp.send("first_name");
}

Server Node js code listening on port 8080:

var http = require('http');
//create a server object:
http.createServer(function (req, res) {
  res.write('Last_name'); //write a response to the client
  res.end(); //end the response
}).listen(8080); //the server object listens on port 8080

What dose the error message mentioned above mean? (The file which is making the http request is in a folder on my desktop. The nodejs file that creates a server to listen on port 8080 is also in the same folder.)

2 Answers2

0

Try allowing Cross-Origin in your server.

http.createServer(function(req,res){
    // Set CORS headers
     res.setHeader('Access-Control-Allow-Origin', '*');
     res.setHeader('Access-Control-Request-Method', '*');
     res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT');
     res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, contentType,Content-Type, Accept, Authorization');
});
lost_in_magento
  • 703
  • 8
  • 22
0

Try adding a 'Access-Control-Allow-Origin' header like so

var http = require('http');
//create a server object:
http
  .createServer(function(req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.write('Last_name'); //write a response to the client
    res.end(); //end the response
  })
  .listen(8080); //the server object listens on port 8080