如何在函数外部提供响应数据

时间:2018-02-24 07:54:48

标签: node.js function http post

从服务器收到的数据被写入变量cols。但它在输出中是空的。我不确定cols现在是否具有适当的值并且可以使用。

    app.post('/get_columns', function (req, res, next) {
          var cols = '';
          var httpreq = http.request(options, function (response) {
            response.on('data', function (chunk) {
              cols += chunk;
              console.log("body: " + cols);
            });
          });
          httpreq.write(options_data);
          httpreq.end();
          console.log('cols: '+cols);
      });

输出结果显示:

cols: 
body: {"ResultSet Output":[{"NAME": "PART_COL1"},{"NAME": "PART_COL2"}],"StatusCode": 200,"StatusDescription": "Execution Successful"}

1 个答案:

答案 0 :(得分:0)

  

HTTP 调用是Node.js中的异步调用,响应是通过事件的多个块。当你在交易时   使用Node.js中的HTTP请求,您必须处理"数据" &安培; "端"   HTTP提供的响应对象上的事件

下面的示例显示了如何处理HTTP中的响应:

app.post('/get_columns', function (req, res, next) {
  var cols = '';
  var httpreq = http.request(options, function (response) {
    // This event is triggered multiple times whenever a chunk is available.
    response.on('data', function (chunk) {
      cols += chunk;
    });

    // This event is triggered once when all the chunks are completed.
    response.on('end', function (chunk) {
      console.log("body: " + cols);
    });
  });
  httpreq.write(options_data);
  httpreq.end();
});

另一种有条理的处理方式

var fetchCols = function (options, options_data) {
  return new Promise((resolve, reject) => {
    var cols = '';
    var httpreq = http.request(options, function (response) {
      // This event is triggered multiple times whenever a chunk is available.
      response.on('data', (chunk) => {
        cols += chunk;
      });

      // This event is triggered once when all the chunks are completed.
      response.on('end', () => {
        resolve(cols);
      });
    });

    // This event is triggered when there is any error.
    httpreq.on('error', (e) => {
      reject(e);
    });
    httpreq.write(options_data);
    httpreq.end();
  });
};

app.post('/get_columns', function (req, res, next) {
  fetchCols(options, options_data)
    .then((cols) => {
      console.log('body: ', cols);
    })
    .catch((err) => {
      console.error('ERR: ', cols);
    });
});