さまざまなバックエンド サービスへの GET および POST http 要求を作成するいくつかのエンドポイントを作成しようとしています。データの形式はすべて非常に似ているため、responseHandler 関数はさまざまなルート関数に何度もコピーされます。再利用のために responseHandler を外部化する方法がある場合。私はそれを移動しようとしましたが、そうすると res への参照が失われます。よりモジュール化された設計に関するヒントはありますか?
routes['/endpoint'] = function(req, res){
console.log("Serving endpoint: /endpoint")
var params={"param": "param-value"}
var options = {
host: 'localhost',
path: '/service?param='+params.param,
method: 'GET'
};
var responseHandler = function(response) {
var data = '';
// keep track of the data you receive
response.on('data', function(chunk) {
data += chunk + "\n";
});
// finished? ok, send the data to the client in JSON format
response.on('end', function() {
res.header("Content-Type:","application/json");
res.end(data);
});
};
// make the request, and then end it, to close the connection
http.request(options, responseHandler).end();
};