Node.js传递variables来路由

我有非常简单的node.js noob问题。 如何将variables传递给导出的路由函数?

路线文件

exports.gettop = function(n, req, res) { console.log(n); res.send(200); }; 

服务器文件

 app.get('/api/v1/top100', routes.gettop(100)); 

错误:.get()需要callback函数,但有一个[对象未定义]

对于你的例子,你想创build一个新的函数,将closures你的价值n 。 在你的情况下,你正在执行gettop并传递返回的值来表示你的路由,这意味着gettop需要返回路由处理程序。

 exports.gettop = function(n){ return function(req, res) { console.log(n); res.send(200); }; }; 

由于你的代码看起来像你正在使用快递,你可以使用快递本地人和expression结果当地人传递variables到你的路线。 虽然其他答案提出了工作解决scheme,但我认为使用快速机制来设置这些variables并不那么突兀。

使用响应本地( 请参阅Express API参考 ),您首先必须在中间件或路由中的某处设置variables。 我将展示中间件方法

 app.use(function(req,res, next) { res.locals.top = 200; next(); }); 

那么在你的路线中,你可以通过res.locals.variablename访问这个属性

 exports.gettop = function(req, res) { console.log(res.locals.top); res.send(200); }; 

如果您想在应用程序范围内进行这些设置,更好的方法是使用应用程序本地( 请参阅Express API参考 )

要设置一个应用程序本地variables,你可以使用

 app.locals.top = 100; 

从你的路线使用这个variables

 exports.gettop = function(req, res){ console.log(req.app.locals.top); res.send(200); }; 

作为loganfsmyth(非常有效!)解决scheme的替代scheme,您可以保留gettop函数并创build一个部分函数:

 app.get('/api/v1/top100', routes.gettop.bind(null, 100));