所以我寫了在服務器端代碼(稱爲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',然後切換了一下路徑。謝謝! –