在Express中使用特定的中间件,除特定之外的所有路径 [英] Use specific middleware in Express for all paths except a specific one

查看:680
本文介绍了在Express中使用特定的中间件,除特定之外的所有路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var app = express.createServer(options ); 
app.use(User.checkUser);

我可以使用 .use 函数一个额外的参数只能在特定路径上使用这个中间件:

  app.use('/ userdata',User.checkUser); 

可以使用路径变量,以便中间件用于除特定的路径之外的所有路径,即根路径?



我在想这样的事情:

  app.use('!/',User.checkUser); 

所以 User.checkUser

解决方案

除了主页,我将添加checkUser中间件到我的所有路径。

  app.get('/',routes.index); 
app.get('/ account',checkUser,routes.account);

  app.all('*',checkUser); 

函数checkUser(req,res,next){
if(req.path =='/')return next();

//验证用户
next();
}

您可以使用下划线扩展它,以在数组中搜索req.path的非验证路径:

  function checkUser(req,res,next){
var _ = require('下划线')
,nonSecurePaths = ['/','/ about','/ contact'];

if(_.contains(nonSecurePaths,req.path))return next();

//验证用户
next();
}


I am using the Express framework in node.js with some middleware functions:

var app = express.createServer(options);
app.use(User.checkUser);

I can use the .use function with an additional parameter to use this middleware only on specific paths:

app.use('/userdata', User.checkUser);

Is it possible to use the path variable so that the middleware is used for all paths except a specific one, i.e. the root path?

I am thinking about something like this:

app.use('!/', User.checkUser);

So User.checkUser is always called except for the root path.

解决方案

I would add checkUser middleware to all my paths, except homepage.

app.get('/', routes.index);
app.get('/account', checkUser, routes.account);

or

app.all('*', checkUser);

function checkUser(req, res, next) {
  if ( req.path == '/') return next();

  //authenticate user
  next();
}

You could extend this with underscore to search for the req.path in an array of non-authenticated paths:

function checkUser(req, res, next) {
  var _ = require('underscore')
      , nonSecurePaths = ['/', '/about', '/contact'];

  if ( _.contains(nonSecurePaths, req.path) ) return next();

  //authenticate user
  next();
}

这篇关于在Express中使用特定的中间件,除特定之外的所有路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆