2017-09-26 22 views
0

所以我寫了在服務器端代碼(稱爲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文檔,但找不到任何東西,所以我在這裏問。謝謝!

回答

0

此代碼:

const router = express.Router; 
app.use("/", router); 

是錯誤的。

如果你想真正創建一個單獨的路由器,你會調用express.Router()構造像真正創建一個新的路由器,然後分配部分航線到新的路由器(doc and example code here):

// call router constructor and then assign some routes to it 
const router = express.Router(); 
router.get('/something, function(req, res) { 
    // handle this route here 
}); 
// hook the router into our instance of express 
app.use("/", router); 

問題的關鍵是express.Router是一個創建路由器的工廠功能。它不是路由器本身。你必須用express.Router()來執行它才能真正製作路由器。

你以前不會發送任何響應,因爲當它試圖執行express.Router,它會調用該函數期待它是中間件的代碼。而且,任何正確實現中間件具有或者發送響應或致電next()到連鎖鏈的下一個中間件/路由。工廠函數既不會做這些(它會在被調用時創建一個新的路由器,而不是實際上成爲路由處理器的正確類型的函數),因此請求只是在那個時候成爲孤立的,從不向客戶端發送任何東西並永遠不會向其他路線處理程序前進。

最終請求將超時。

+0

謝謝!我把''''''''app.use'換成了'router.use',然後切換了一下路徑。謝謝! –