ExpressJS:是否可以在同一路由的不同路由功能之间共享变量?

时间:2016-05-09 15:22:27

标签: node.js express

在不同路由功能中获取和处理查询参数时,必须在每个路由功能中定义相同的内容。

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));
});

虽然这样做是可以理解的,因为函数的范围不同,看起来有点多余,而且反对 的一般规则不要重复 必须为完全相同的var processed_query = process_function(req.query);重复定义相同的变量req.是否有一种(更好)的方式只做一次?

1 个答案:

答案 0 :(得分:2)

您可以将计算变量存储在req对象的某些属性中。 E.g。

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));
});