node.js - Nodejs 全局中间件

标签 node.js express routes middleware

我们如何将中间件添加到 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.useapp.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/

相关文章:

node.js - sequelize 是否有自动迁移的工具?

javascript - 调用退出错误后无法将查询排入队列

node.js - 使用 nginx 和express.js 的静态站点 - 身份验证

node.js - 在 Docker 镜像中创建 Let's Encrypt 证书和 Certbot

javascript - NestJS 根据浏览器语言传递静态文件

node.js - 为什么 Node.js Postgres Wiki 示例会在每个 http 请求中插入多条记录?

javascript - 有没有办法将数据从 HTML(使用 ejs 模板引擎)发送到 Node.js?

java - 如何使用 Google map 客户端 java api 优化 Google map 中的路线。

php - silex 如何使路由结束 "/"可选

javascript - 套接字 io : how to pass paramter to disconnet socket event?