【发布时间】:2015-09-11 21:20:37
【问题描述】:
我正在使用 expressJs 并希望在每个结束时执行一些中间件 请求。
是否可以在应用程序级别定义它以避免定义它 在每条路线上?
【问题讨论】:
-
感谢您的快速回复。它不是重复的,但 expressJs 钩子正是我需要放置中间件并解决我的问题。
我正在使用 expressJs 并希望在每个结束时执行一些中间件 请求。
是否可以在应用程序级别定义它以避免定义它 在每条路线上?
【问题讨论】:
检查这个例子。代码“console.log('Response sent')”将在对任何路由的每个请求结束时执行。
var express = require('express');
var app = express();
function myMiddleware (req, res, next) {
res.on('finish', function() {
console.log('Response sent.');
});
next();
}
app.use(myMiddleware);
app.get('/first', function(req, res, next) {
console.log('[/first] New request recieved.');
res.end('Hi!');
});
app.get('/second', function(req, res, next) {
console.log('[/second] New request recieved.');
res.end('Hi!');
});
app.listen(3000, function(req, res) {
console.log('Listening port 3000');
});
【讨论】:
您可以为此使用app.use([path,] function [, function...])。
这里有一个来自 Express'docs 的示例:
// this middleware will be executed for every request to the app
app.use(function (req, res, next) {
console.log('Time: %d', Date.now());
next();
})
当然,您可以在别处定义一个函数并将其传递给use 方法。
function middleware(req, res, next) {
console.log('middleware!');
next();
}
// some other codes maybe
app.use(middleware);
【讨论】:
var app = express(); 初始化您的应用程序后,您只需放置中间件即可。在上述答案之上,我试图证明您可以在任何地方定义中间件并将其作为参数传递。我希望现在更清楚一点。