所以我写了在服务器端代码(称为app.js):快递/ node.js的app.use使得客户端滞后了
console.log("Server started. If you're reading this then your computer is still alive."); //Unnecessary test command to make sure everything works.
var express = require("express");
var app = express();
var serv = require("http").Server(app);
const router = express.Router;
app.get("/", function(req, res) {
res.sendFile(__dirname + "/client");
});
app.use("/", router);
app.use("/client", express.static(__dirname + "/client"));
serv.listen(2000);
//Set up server stuff. This isn't touched.
var io = require("socket.io")(serv, {});
io.sockets.on("connection", function(socket) {
console.log("Socket connection"); //This will print to the server, not the developer console in your browser.
});
//Initialize sockets and set up socket listeners. This isn't touched either, except when adding new events.
console.log("Ok"); //Just make sure.
而且我有一个客户端:
<!DOCTYPE html>
<html>
<head>
<title>Multiplayer!</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<script>
var socket = io();
</script>
</body>
</html>
当我在终端运行node app.js
,然后在我的浏览器上转到localhost:2000时,加载需要一两分钟,然后说“本地主机没有发送任何数据”(在Chrome上)。当我注释掉app.use("/", router);
,它加载很好(这是行不通的,因为它不能GET /
),所以我知道有蹊跷的是行,但我不知道是什么。我环顾了快速API文档,但找不到任何东西,所以我在这里问。谢谢!
谢谢!我把''''''''app.use'换成了'router.use',然后切换了一下路径。谢谢! –