Express:从另一个中间件调用中间件

我是新来Express 4 ,我想知道如何实现这件事情的东西:我使用jwt来validation我的API的消费者,做到这一点,我有一个非常简单的中间件来检查jwt令牌的有效性:

var requireValidToken = function(req, res, next) { var token = req.body.token || req.query.token || req.headers['x-access-token']; if (token) { try { var decoded = jwt.verify(token, req.app.get('superSecret')); } catch(err) { return res.json({ success: false, message: 'Failed to authenticate token.' }); } req.user = decoded.user; next(); } else { return res.status(403).send({ success: false, message: 'No token provided.' }); } }; 

这是工作得很好,但现在,我想扩大这个能够检查用户的angular色:

  router.get('/anAdminRoute', requireRole('ROLE_ADMIN'), function (req, res, next) { // some code... }); 

所以我为此添加了一个中间件:

 var requireRole = function(role) { return function(req, res, next){ // Dummy tests... if(req.user.role == roles.admin || req.user.role == role){ next(); } else { return res.status(403)({ success: false, message: "Token valid, but you don't have the right permission to access this resource :)" }); } } } 

但是,因为这requireRole()函数,而显然检查一个有效的jwt令牌,我想知道我怎么可以在这个函数中调用我的requireValidToken中间件,所以不必显式调用我想要保护的每个路由。

一个简单的解决scheme将不会使用requireValidToken作为中间件,但我仍然希望能够使用它来保护某些路线

编辑:解决scheme

链接中间件是这样简单的:

 var middleware2 = function(param) { return function(req, res, next){ middleware1(req, res, function(){ // middleware2 code }); } } 

如果有人感兴趣,我的最终工作解决scheme来validation用户angular色:

 var jwt = require('jsonwebtoken'), roles = require('../models/user').roles; // authentication middleware // check if the given jwt token is valid var requireValidToken = function(req, res, next) { var token = req.body.token || req.query.token || req.headers['x-access-token']; if (token) { try { var decoded = jwt.verify(token, req.app.get('superSecret')); } catch(err) { return res.json({ success: false, message: 'Failed to authenticate token.' }); } req.user = decoded.user; next(); } else { return res.status(403).send({ success: false, message: 'No token provided.' }); } }; var requireRole = function(role) { return function(req, res, next){ requireValidToken(req, res, function(){ if(req.user.role == roles.admin || req.user.role == role){ next(); } else { return res.status(403).send({ success: false, message: "Token valid, but you don't have the right permission to access this resource :)" }); } }); } } module.exports = { requireValidToken: requireValidToken, requireRole: requireRole } 

       

网上收集的解决方案 "Express:从另一个中间件调用中间件"

完全误解你的问题。 如果您想在某些情况下调用requireValidToken ,则可以将req和res对象与匿名callback一起传递给中间件函数。 如何获得中间件function在很大程度上取决于您的应用程序体系结构,所以我会假设我在我的上下文中有requireValidToken

 var requireRole = function(role) { return function(req, res, next){ // Dummy tests... requireValidToken(req, res, function () { if(req.user.role == roles.admin || req.user.role == role){ next(); } else { return res.status(403)({ success: false, message: "Token valid, but you don't have the right permission to access this resource :)" }); } }); } };