node.js express.js 上的过滤器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8763504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filters on express.js
提问by rizidoro
I want to do a filter like rails before filter on express.js. I have a file named photo.js where I'm putting all my photo related routes on there. But I need to redirect user that is not authenticated on my system to the login page. I want to do an beforeFilter so then I dont need to put that logic in all my routes...
我想在 express.js 上过滤之前做一个像 rails 这样的过滤器。我有一个名为 photo.js 的文件,我将所有与照片相关的路线放在那里。但是我需要将未在我的系统上进行身份验证的用户重定向到登录页面。我想做一个 beforeFilter 所以我不需要把这个逻辑放在我所有的路线中......
Thanks
谢谢
回答by Dave Jensen
If you want to keep everything in your photo.js file, I think a better approach is to use app.all and pass multiple callbacks (which work like middleware in routing) built into the app routing. For instance
如果您想将所有内容保留在 photo.js 文件中,我认为更好的方法是使用 app.all 并传递内置于应用程序路由中的多个回调(类似于路由中的中间件)。例如
app.all('/photo/*', requireAuthentication, loadUser);
app.get('/photo/view', function(req, res) {
res.render('photo_view');
});
app.get('/photo/list', function(req, res) {
res.render('photo_list');
});
Where requireAuthenticationand loadUserare functions.
whererequireAuthentication和loadUserare 函数。
Take a look the documentation for app.VERB and app.all at http://expressjs.com/api.html#app.all
在http://expressjs.com/api.html#app.all查看 app.VERB 和 app.all 的文档
回答by tjholowaychuk
There are extensions or higher-level frameworks like express-resource.
有扩展或更高级别的框架,如express-resource。
回答by Peter Lyons
The rails before_filter concept maps closely to the middleware concept from connect, which is part of express. You can set this up manually by preceding each photo related route with your authentication function, or use something high-level like TJ has mentioned. To do it manually would just be a matter of something like this (pseudo-coffeescript)
rails before_filter 概念与 connect 中的中间件概念密切相关,后者是 express 的一部分。您可以通过在每个与照片相关的路线之前使用您的身份验证功能来手动设置它,或者使用像 TJ 提到的高级内容。手动执行此操作只是这样的问题(伪咖啡脚本)
myAuthMiddleware = (req, res, next) ->
if not req.session.user?
res.redirect "/"
else
next()
editPhoto = (req, res) ->
....
deletePhoto = (req, res) ->
....
app.use(myAuthMiddleware, func) for func in [editPhoto, deletePhoto]
What that is saying is use myAuthMiddlewarelike a before_filter for the editPhotoand deletePhotomiddleware functions.
这就是说myAuthMiddleware像 before_filtereditPhoto和deletePhoto中间件函数一样使用。

