如何在 JavaScript 中发出 http 请求

问题描述

我正在做一个关于 JavaScript 中的 HttpRequest 的快速练习。我想从本地主机获取数据。所以在客户端发出如下请求。

  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)
    }
  }

和服务器端

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

但是,它不起作用,我无法在客户端获取用户名数据。我应该如何修改代码

解决方法

看看the introductory documentation for Express

路由是使用路径定义的,而不是完整的 URL。

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

请注意,如果您不是从 Express 服务器加载 HTML 文档,则必须use CORS to grant permission to read the JSON across origins