ExpressJS应用程序中的中间件使用next()来调用自身

时间:2015-05-13 13:26:16

标签: node.js express middleware

我有一个基本的ExpressJS服务器,它只是用来记录连接的IP,并提供静态的页面。当我自己连接它时会发生什么,记录请求的IP的中间件会多次重复。如果我删除对next()的调用,则会停止,但它也会阻止管理静态页面的中间件运行。

服务器的代码是:

var express = require('express');

    app = express();

app.use(function(req, res, next) {
    console.log('Received a connection from: ' + req.ip)
    next();
})

app.use('/', express.static(__dirname + '/public'));

var port = 55671;
app.listen(port, function() { 
    console.log('Listening on: ' + port);
});

如果我只连接一次,这是标准输出:

Listening on: 55671
Received a connection from: ::ffff:127.0.0.1
Received a connection from: ::ffff:127.0.0.1
Received a connection from: ::ffff:127.0.0.1
Received a connection from: ::ffff:127.0.0.1
Received a connection from: ::ffff:127.0.0.1
Received a connection from: ::ffff:127.0.0.1
Received a connection from: ::ffff:127.0.0.1
Received a connection from: ::ffff:127.0.0.1
Received a connection from: ::ffff:127.0.0.1

我已经尝试过不同的中间件排序,我以为这是以前工作的,但我可能记错了。 为什么next()调用多次调用一个中间件然后再移动到另一个中间件然后停止?

1 个答案:

答案 0 :(得分:0)

它不是下一个()多次调用的东西。它只允许您向前移动,否则您的应用程序会在第一个日志声明后停滞。

但是,中间件顺序很重要,这里将为所有访问的静态文件调用日志记录中间件。

如果您不想跟踪那些静态中间件,请将静态中间件放在记录之前。