确保变量正确地传递到中间件函数。一种解决方式是使用req对象的属性来存储变量。例如,在路由处理器函数中,如果要将变量传递到中间件函数中,可以使用req对象来存储该变量,然后将req对象作为参数传递给中间件函数。
代码示例:
app.get('/middleware-route', function(req, res, next) { var myVariable = 'Hello World'; req.myVariable = myVariable; // 存储变量在req对象上 next(); });
app.use(function(req, res, next) { console.log(req.myVariable); // 输出: Hello World next(); });
上一篇:变量没有被正确赋值