ExpressJS 应用中的中间件使用 next() 调用自身
Middleware in ExpressJS app uses next() to call itself
我有一个基本的 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() 调用在移动到另一个中间件然后停止之前多次调用一个中间件?
不是 next() 多次调用 thing。它只允许您继续前进,否则您的应用程序会在第一个日志语句之后卡住。
但是,中间件的顺序很重要,这里将为访问的所有静态文件调用您的日志记录中间件。
如果不想跟踪静态中间件,最好将静态中间件放在日志中间件之前。
我有一个基本的 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() 调用在移动到另一个中间件然后停止之前多次调用一个中间件?
不是 next() 多次调用 thing。它只允许您继续前进,否则您的应用程序会在第一个日志语句之后卡住。
但是,中间件的顺序很重要,这里将为访问的所有静态文件调用您的日志记录中间件。
如果不想跟踪静态中间件,最好将静态中间件放在日志中间件之前。