路由器的Express / node.js app.use使客户端延迟

时间:2017-09-26 00:35:09

标签: javascript node.js express

所以我在服务器端编写了这段代码(称为app.js):

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时,需要一两分钟才能加载,然后说“localhost没有发送任何数据”(在Chrome上) 。当我注释掉app.use("/", router);时,它会很好地加载(它不起作用,因为它不能GET /),所以我知道那条线有问题,但我不知道是什么。我查看了快速API文档,但找不到任何内容,所以我在这里问。谢谢!

1 个答案:

答案 0 :(得分: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()以链接到链中的下一个中间件/路由。 express.Router工厂函数不执行这些操作(它在调用时创建一个新的路由器,并且它本身不是一个实际上是路由处理程序的正确类型的函数)所以请求只是在那个时候被孤立,从不发送任何对客户而言都没有进入其他路线处理人员。

最终请求会超时。