I can not send a local request from my js file to node js both on my computer, here’s how I do it here is node js
var http=require('http'); var model={name:"aaaavava"} http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/plain'}); response.end(JSON.stringify(model)); }).listen(8081); // Console will print the message console.log('Server running at http://127.0.0.1:8081/'); and here is how I send a request
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <button onclick="loadPhones()" id="button">Загрузить json!</button> <script> function loadPhones() { var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://127.0.0.1:8081/', true); xhr.send(); xhr.onreadystatechange = function() { if (xhr.readyState != 4) return; button.innerHTML = 'Готово!'; if (xhr.status != 200) { alert(xhr.status + ': ' + xhr.statusText); } else { alert(xhr.responseText); document.write(xhr.responseText); console.log(JSON.parse(xhr.responseText)); } } button.innerHTML = 'Загружаю...'; button.disabled = true; } </script> </body> </html> I get this error
Failed to load http://127.0.0.1:8081/: The 'Access-Control-Allow-Origin' header has a value 'http://localhost:8888' that is not equal to the supplied origin. Origin 'null' is therefore not allowed access. although the nodejs file works through the browser
XMLHttpRequestdirectly in 2018 о_О - Suvitruf ♦