可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
回答1:
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();
}
回答2:
Instead of directly registering User.checkUser
as middleware, register a new helper function, say checkUserFilter
, that gets called on every URL, but passed execution to userFiled` only on given URLs. Example:
var checkUserFilter = function(req, res, next) {
if(req._parsedUrl.pathname === '/') {
next();
} else {
User.checkUser(req, res, next);
}
}
app.use(checkUserFilter);
In theory, you could provide regexp paths to app.use
. For instance something like:
app.use(/^\/.+$/, checkUser);
Tried it on express 3.0.0rc5, but it doesn't work.
Maybe we could open a new ticket and suggest this as a feature?
回答3:
You can set the middleware one each route also.
// 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)
})
回答4:
Use
app.use(/^(\/.+|(?!\/).*)$/, function(req, resp, next){...
This pass any url apart from /. Unless, it works for me.
In general
/^(\/path.+|(?!\/path).*)$/
(see How to negate specific word in regex?)
Hope this helps