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

  • Use XMLHttpRequest directly in 2018 о_О - Suvitruf
  • one
    Yes, even carts would transport your ajax, what's the problem? :) Offer the same option better than making big eyes. - zalex 2:58 pm

1 answer 1

I suspect that when entering your local page, you type http: // localhost: 8888 , but you want the server at 127.0.0.1 to correctly receive your Ajax requests.

Strictly speaking, localhost and 127.0.0.1 as a domain name are not the same thing.

Then either go to 127.0.0.1 or run both servers on localhost.

You can get into this topic by reading this document.