2017-04-09 73 views
0

我在我的应用程序中使用名为Grant的库。之前我已经将它包含在上面链接的自述文件中的示例中,但是现在我需要有条件地包含它,并且我似乎无法使其工作。如何有条件地使用Express包含子应用程序?

它是如何

const grant = new Grant(grantConfig); 
app.use(grant); 

我已经在快递之前完成条件中间件工作过,所以我想包括格兰特不会是一个问题。

我怎样努力(不工作)

const grant = new Grant(grantConfig); 

app.use((req, res, next) => { 
    if (someBooleanVariable) { 
     next(); 
    } else { 
     grant(req, res, next); 
    } 
}); 

所以这是行不通的。我认为这可能与Grant作为Express的一个实例而不是普通的中间件功能有关,但我不确定。您可以看到Grant如何实施here。 Express文档表示应该对待它,但我也可能会误解它们。

注:我需要这个工作在每个请求的基础上,因此中间件风格的方法。

+0

你试过app.use(补助金);在这个else语句里面? –

+0

您是否真的需要在每个请求的基础上使用它,或者您是否只需要它用于特定路由? – robertklep

+0

当我尝试它时,app.use(grant)不起作用。理想情况下,我需要在路线的一个子集上使用它。 –

回答

1

如果要使用特定的中间件仅路线的一个子集:

// On a single route: 
app.get('/some/route', grant, function(req, res) { 
    ... 
}); 

// On a set of routes with a particular prefix: 
app.use('/api', grant, apiRouter); 

// On a specific router: 
let apiRouter = express.Router(); 

apiRouter.use(grant); 
apiRouter.get(...); 
相关问题