0

I am facing the below error when trying to access a local node server. Someone please help me solve this issue.

XMLHttpRequest cannot load http://localhost:3000/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

<!DOCTYPE html>
<html>
<head>
    <title>Test Service</title>
</head>
<body >
<script>
    function _service(url, callback) {
      var httpRequest;
      if (window.XMLHttpRequest) {
        httpRequest = new XMLHttpRequest();
      } else if (window.ActiveXObject) {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
      }

      httpRequest.onreadystatechange = function() {
        if (httpRequest.readyState === 4 &&
          httpRequest.status === 200) {
          callback.call(httpRequest.responseText, "abc", "xyx");
        }
      };
      httpRequest.open('GET', url);
      httpRequest.setRequestHeader('Access-Control-Allow-Headers', '*');
      httpRequest.setRequestHeader('Content-type', 'application/ecmascript');
      httpRequest.setRequestHeader('Access-Control-Allow-Origin', '*');
      httpRequest.send();
    }

    function _one(a){
        if(!a){
            _service("http://localhost:3000", function() {
              var a = JSON.parse(this);
              _one(a)
            });     
        }else{
            console.log(a);
        }
    }
    _one();

</script>
</body>
</html>

and my node server is below.

var http = require("http");
var server = http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/html"});
  response.write("Welcome to node js");
  response.end();
});

server.listen(3000, (err) => {  
  if (err) {
    return console.log('something bad happened', err)
  }
});

I am just running my node server by node index.js which is the node file. Both the files are in same folder.

Raviteja Avvari
  • 252
  • 4
  • 14
  • `httpRequest.setRequestHeader('Access-Control-Allow-Headers', '*');` — Those are response headers, not request headers. – Quentin Dec 16 '16 at 09:58
  • `httpRequest.setRequestHeader('Content-type', 'application/ecmascript');` — You are making a GET request. There is no request body to describe the content-type of. Don't do that. – Quentin Dec 16 '16 at 09:59

0 Answers0