微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 JavaScript 中发出 http 请求

如何解决如何在 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。