javascript - 为什么此服务器/客户端连接不起作用?
问题描述
我正在使用 node.js 设置我的第一台服务器,但我不知道如何连接客户端和该服务器。我不想使用 jquery,我能找到的所有关于这个的问题都涉及 jquery 或者关于不同的语言。有谁知道如何做到这一点?
编辑:我在服务器和客户端之间建立了连接,但响应中没有任何内容。我的服务器的代码在这里,我的客户端的代码在这里(在“多人游戏”文件夹中)。
解决方案
做这样的事情来设置一个侦听端口 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
推荐阅读
- python - 处理日期时间字符串中秒的小数部分的七位数字
- php - 使用 PHP 正则表达式对内容中的多个短代码进行分组
- c++ - 为什么在触发 WM_COMMAND 时 WM_KEYDOWN 不起作用?
- sql - 查询只返回两列?
- sql - 选择转换的列时如何使用 COUNT 和 GROUP BY(或类似的替代方法)
- laravel - 如何在其他模型的另一个关系中使用关系?
- php - Symfony - 在接口内获取容器
- laravel - Laravel TestCase-> postJson 到外部网址?
- rust - Trait 的类型成员必须是 Send
- angular - 在我的角度输入字段中添加很棒的字体