Search code examples
javascripthttpxmlhttprequest

Access to XMLHttpRequest at '...' from origin 'http://...' has been blocked by CORS policy


So my problem is:

Whenever I try to make an XMLHttpRequest to my HTTP server from my web page (same machine, different port), I get blocked with this error:

Access to XMLHttpRequest at 'localhost:8081' from origin 'http://localhost:8080' has been blocked by CORS policy:
Cross-origin requests are only supported for protocol schemes: HTTP, data, chrome, chrome-extension, brave, chrome-untrusted, HTTPS.

Why does this happen?

Sample client (Browser):

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    // Use data...
};
xhttp.open("GET", "localhost:8081", true);
xhttp.send();

Sample server (NodeJS, HTTP library):

const server = http.createServer((req, res) => {
  if(req.url != '/') return res.end('404');
  res.writeHead(200, {
    'Content-Type': 'text/html'
  })

  const json = {
    // Data...
  }

  res.write(JSON.stringify(json))
  res.end()
});

server.listen(8081)

Solved, thanks to Quentin in the comments :D


Solution

  • The answer is here.

    It's a problem with the privacy of your browser and there are two ways that you could fix it:

    1. Allowing requests from everywhere on your browser
    2. Put controllers inside the header access control information.

    The entire answer is on the link above