ExpressJS:是否可以在不同路由function之间共享相同路由的variables?

在不同的路由function中获取和处理查询参数时,必须在每个路由function中定义相同的事物。

router.get("/", function(req, res, next){ var processed_query = process_function(req.query); //do some thing based on the query string console.log(processed_query); next(); }, function(req, res, next){ var processed_query = process_function(req.query); //this needs to be defined again //do some different thing based on the query string res.write(JSON.stringify(processed_query)); }); 

尽pipe这样做是可以理解的,因为函数的作用域是不同的,看起来有点多余,而且不要重复自己必须重复定义相同的variablesvar processed_query = process_function(req.query); 为完全相同的req. 是否有一个(更好)的方法做一次?

您可以将您的计算variables存储在req对象的某个属性中。 例如

 router.get("/", function(req, res, next){ var processed_query = process_function(req.query); //do some thing based on the query string console.log(processed_query); req.processed_query = processed_query; next(); }, function(req, res, next){ var processed_query = req.processed_query; //do some different thing based on the query string res.write(JSON.stringify(processed_query)); });