我正在使用具有一些中间件功能的node.js中的Express框架:
var app = express.createServer(options);
app.use(User.checkUser);
我可以将.use
函数与附加参数一起使用,以仅在特定路径上使用此中间件:
app.use('/userdata', User.checkUser);
是否可以使用path变量,以便中间件可用于除特定路径(即根路径)以外的所有路径?
我正在考虑这样的事情:
app.use('!/', User.checkUser);
所以User.checkUser
总是被调用,除了根路径。
我将把checkUser中间件添加到我的除首页之外的所有路径中。
app.get('/', routes.index);
app.get('/account', checkUser, routes.account);
或
app.all('*', checkUser);
function checkUser(req, res, next) {
if ( req.path == '/') return next();
//authenticate user
next();
}
您可以使用下划线扩展此名称,以在未经身份验证的路径数组中搜索req.path:
function checkUser(req, res, next) {
var _ = require('underscore')
, nonSecurePaths = ['/', '/about', '/contact'];
if ( _.contains(nonSecurePaths, req.path) ) return next();
//authenticate user
next();
}
不是直接将User.checkUser
注册为中间件,而是注册一个新的帮助程序函数,例如checkUserFilter
,该函数在每个URL上都被调用,但仅在给定URL上将执行传递给userFiled`。示例:
var checkUserFilter = function(req, res, next) {
if(req._parsedUrl.pathname === '/') {
next();
} else {
User.checkUser(req, res, next);
}
}
app.use(checkUserFilter);
理论上,您可以提供app.use
的正则表达式路径。例如:
app.use(/^\/.+$/, checkUser);
在express 3.0.0rc5上尝试过,但是不起作用。
也许我们可以open a new ticket并建议将此作为功能吗?
您也可以在每个路由上设置中间件。
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
if (!req.body) return res.sendStatus(400)
res.send('welcome, ' + req.body.username)
})
使用
app.use(/^(\/.+|(?!\/).*)$/, function(req, resp, next){...
此除了/以外的所有网址。除非,它对我有用。
一般
/^(\/path.+|(?!\/path).*)$/
(请参阅How to negate specific word in regex?)
希望这会有所帮助
使用此名为express-unless的库
除非路径为index.html,否则需要对每个请求进行身份验证。
app.use(requiresAuth.unless({
path: [
'/index.html',
{ url: '/', methods: ['GET', 'PUT'] }
]
}))
路径可以是字符串,正则表达式或其中任何一个的数组。它也可以是一个对象数组,它是URL和方法密钥对。如果请求路径或路径和方法匹配,则中间件将不会运行。
此库肯定会为您提供帮助。