在Express中使用特定的中间件,除特定之外的所有路径 [英] Use specific middleware in Express for all paths except a specific one
问题描述
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屋!