Filters on express.js

后端 未结 3 708
南笙
南笙 2021-02-04 07:14

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

相关标签:
3条回答
  • 2021-02-04 07:44

    There are extensions or higher-level frameworks like express-resource.

    0 讨论(0)
  • 2021-02-04 07:45

    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)

    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 myAuthMiddleware like a before_filter for the editPhoto and deletePhoto middleware functions.

    0 讨论(0)
  • 2021-02-04 07:51

    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

    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 requireAuthentication and loadUser are functions.

    Take a look the documentation for app.VERB and app.all at http://expressjs.com/api.html#app.all

    0 讨论(0)
提交回复
热议问题