我正在尝试编写几个端点来向各种后端服务发出 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();
};