问题
I want to prevent access to someone not logged-in to any url that starts with '/users'
Here's my current code:
app.use('/^users*',function (req, res, next) {
if (checkAuth(req)) {
console.log('authorization OK');
next();
} else {
console.log('authorization failed');
res.redirect('/login');
}
});
function checkAuth(req) {
console.log('req',req.url);
if (!req.session.user_id && req.url !== '/login' && req.url !== '/') {
return false;
}
return true;
};
but the regular expression I have is not right. I can't find a regular expression for expression that matches "everything that starts with 'user'". This should be easy, but is proving more difficult than expected.
According to the Express API documentation:
// will match paths starting with /abcd
app.use('/abcd', function (req, res, next) {
next();
})
回答1:
app.all('*/users/*', requireAuthentication, function (req, res, next){
});
Above route will catch all kind of requests starting from users, will through requireAuthentication function, then following function on next().
回答2:
Try app.use('/users/?*', function(){}); That should match all routes starting with /users
回答3:
Do not use single quote marks '/^users*' use /^\/users*. That is for all strings beginning with '/users'.
But if just want it to be hierarchial as '/users/foo' you do not need regex you could use:
app.use('/users/*',function (req, res, next)
app.use express API reference
来源:https://stackoverflow.com/questions/27466468/node-js-express-prevent-access-to-certain-urls