将中间件包装为函数声明

时间:2017-02-16 22:13:07

标签: javascript node.js express passport.js

如何构建中间件以将其传递给路由处理程序而不立即调用它?

// Changing this
import auth from '../middleware/auth'

userRouter.get('/dashboard', auth().authenticate(), function(req, res) {
  res.send('It worked! User id is: ' + req.user.id)
})

// To this
import auth from '../middleware/auth'

userRouter.get('/dashboard', auth.authenticate, function(req, res) {
  res.send('It worked! User id is: ' + req.user.id)
})

中间件功能

middleware/auth.js

module.exports = function() {
  var strategy = new JwtStrategy(options, function(payload, done) {
    (...)
  });
  (...)
  return {
    initialize: () => {
      return passport.initialize();
    },
    authenticate: () => {
      return passport.authenticate("jwt", { session: false });
    }
  };
};

我想我必须将req, res, next传递给authenticate,但是如何将其传递给passport.authenticate

1 个答案:

答案 0 :(得分:0)

一半,穷人解决方案。不允许额外处理。

module.exports = function() {
  var strategy = new JwtStrategy(options, function(payload, done) {
    (...)
  });
  (...)
  return {
    initialize: () => {
      return passport.initialize();
    },
  authenticate: passport.authenticate("jwt", { session: false })
};