Javascript 有没有办法在nodejs中创建一个通用响应处理程序?

Javascript 有没有办法在nodejs中创建一个通用响应处理程序?,javascript,node.js,Javascript,Node.js,我正在尝试编写两个端点,它们将向各种后端服务发出GET和POST http请求,数据的格式都将非常相似,因此responseHandler函数将被一次又一次地复制到不同的路由函数,我想知道是否有一种方法将responseHandler外部化以供重用。我试着把它移走,但是我会失去对res的参考。有人对更模块化的设计有什么建议吗 routes['/endpoint'] = function(req, res){ console.log("Serving endpoint: /endpoint

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

一般来说,我认为您可以在lib中创建一个名为responseHandlers的文件夹,添加一个包含以下内容的文件

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);
  });
};
exports.Handler = responseHandler;
将其另存为whateverHandler.js,然后创建一个index.js文件,该文件需要whatever.js并将其导出到Handler。这样,如果将来需要添加更多处理程序,只需添加一个文件并更新index.js即可。要使用,请在路由处理程序中执行以下操作

var handler = require('./lib/responseHandlers').whateverHandler;
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'
    };
};

// make the request, and then end it, to close the connection
http.request(options, handler).end();
};

您可以将
responseHandler
转换为函数生成器,并传入
res
对象,以免丢失它:

var responseHandler = function(res) {
  return 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);
    });
  };
}
然后像这样使用它:

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

    // make the request, and then end it, to close the connection
    http.request(options, responseHandler(res)).end();
};

啊,我试过用repsonse,res作为输入,所以它不起作用…不知道我不必传入响应对象。
http.request
response
对象传入您传递它的任何函数。