0

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

2 回答 2

0

通常我认为你可以在你的库中创建一个名为 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,然后创建一个需要whatever.js 的index.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();
};
于 2012-11-15T17:06:26.253 回答
0

你可以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();
};
于 2012-11-15T17:38:43.600 回答