2016-05-09 8 views
1

異なるルーティング機能内でクエリパラメータを取得して処理する際、各ルーティング機能内で同じものを定義する必要があります。ExpressJS:同じルートの異なるルーティング機能間で変数を共有することは可能ですか?

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.一度だけ行う(より良い)方法はありますか?

答えて

2

計算された変数は、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)); 
}); 
+0

はい、いい考えです。私はreqオブジェクト自体を使うことができます。ありがとう! – Yogesch

関連する問題