我们如何将中间件添加到 app.use()
并仅在我们调用它时使用该中间件。目前我有这段代码:
function ensureUser(req,res,next){
if(req.isAuthenticated()) next();
else res.send(false);
}
app.get('/anything', ensureUser, function(req,res){
// some code
})
我正在尝试将 ensureUser 添加到我有路由的所有文件中。我提出了一种解决方案,将该文件添加到一个文件中,并在我有路由的每个文件中都需要该文件。有没有办法将该功能添加到 app.use
或 app.all
或类似的东西,这样我就不必在每个文件中都包含该功能.
最佳答案
是的,添加一个 app.use()
在你的任何路由之前,没有第一个参数并且应该总是调用那个:
app.use(function(req, res, next){
if(req.isAuthenticated()) next();
else res.send(false);
});
// routing code
app.get('/', function(req, res){});
app.get('/anything', function(req,res){})
//...
这样您就不必在每个文件中都包含它。但是,通过这种方式,您还需要对每个文件进行身份验证,因此您可能想要添加一些异常(exception)情况(至少是身份验证页面)。为此,您可以在 url with a wildcard 中包含该方法:
app.use('/admin/*', function(req, res, next){
if(req.isAuthenticated()) next();
else res.send(false);
});
或者在函数内部添加白名单:
app.use(function(req, res, next){
// Whitelist
if(['/', '/public'].indexOf(req.url) !== -1
|| req.isAuthenticated())
next();
else
res.send(false);
}
关于node.js - Nodejs 全局中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32803390/