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
http://
bit of the URL. – Eddington'Content-Type': 'text/html'
andres.write(JSON.stringify(json))
really doesn't make sense. JSON is not HTML. – Eddington