0

I'm doing a quick exercise about HttpRequest in JavaScript. I want to get data from the localhost. So made a request in client end like below.

  var httpRequest = new XMLHttpRequest();
  httpRequest.open('GET', 'http://localhost:4000/', true);
  httpRequest.send;

  httpRequest.onreadystatechange = function(){
    if(httpRequest.readyState ==4 && httpRequest.status ==200){
      var json = httpRequest.responseText;
      console.log(json)
    }
  }

And the server side

app.get('http://localhost:4000/',(req,res) => {
  res.status(200).send({username: "123"})
})

However, it doesn't work, I can't get the username data in client. How should I MODIFY the code?

Jesse
  • 17
  • 2

1 Answers1

0

Look at the introductory documentation for Express.

The route is defined using only the path, not the full URL.

app.get('http://localhost:4000/',(req,res) => {
  res.status(200).send({username: "123"})
})

Note that if you aren't loading the HTML document from your Express server you will have to use CORS to grant permission to read the JSON across origins.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335