首页 > 解决方案 > 为什么此服务器/客户端连接不起作用?

问题描述

我正在使用 node.js 设置我的第一台服务器,但我不知道如何连接客户端和该服务器。我不想使用 jquery,我能找到的所有关于这个的问题都涉及 jquery 或者关于不同的语言。有谁知道如何做到这一点?

编辑:我在服务器和客户端之间建立了连接,但响应中没有任何内容。我的服务器的代码在这里,我的客户端的代码在这里(在“多人游戏”文件夹中)。

标签: javascriptnode.js

解决方案


做这样的事情来设置一个侦听端口 8080 的 Node.js HTTP 服务器。

客户端将使用 AJAX 发送 GET 请求。


索引.html

<html>
  <head>
    <script>
      var xhttp = new XMLHttpRequest();
      // Create a function callback, called every time readyState changes
      xhttp.onreadystatechange = function()
      {
        // When the response has been received with status 200
        // Update the element div#response-holder
        if (this.readyState == 4 && this.status == 200)
        {
          var txtDisplay = elem document.getElementById("response-holder")
          txtDisplay.innerHTML = this.responseText;
        }
      };

      // Send a GET request to /api, asynchronously
      xhttp.open("GET", "/api", true);
      xhttp.send();
    <script>
  </head>
  <body>
    <div id="response-holder"></div>
  </body>
</html>"

服务器.js

// Load the http and fs (filesystem) modules
var app = require("http");
var fs = require("fs");

// Serve the "/index.html" home page on port 8080
app.createServer(function (req, resp)
{
  fs.readFile("index.html", function(err, data)
  {
    resp.writeHead(200, {'Content-Type': 'text/html'});
    resp.write(data);
    resp.end();
  }
  );
}
).listen(8080);

// Also answer to GET requests on "/api"
app.get('/api', function(req, resp)
{
  var responseStr = "Hello World!";
  resp.status(200);
  resp.setHeader('Content-type', 'text/plain');
  return resp.send(responseStr);
}
);

这是关于 AJAX 的 W3Schools 教程: https ://www.w3schools.com/js/js_ajax_intro.asp


推荐阅读