Node.js http.get返回" undefined"在功能上

时间:2016-12-28 02:09:18

标签: node.js



var exports = module.exports = {};
var http = require('http');

exports.get = function(key, app, vari) {
    http.get('<url here>/?key='+key+'&app='+app+'&var='+vari+'&req=0', function (response) {
        response.setEncoding('utf8');
        response.on('data', function(body) {
            console.log(body);
            return body;
        });
    });
};
&#13;
&#13;
&#13;

我的代码(见上文)会很好地将响应输出到控制台,但是当尝试在导出中使用该函数时,它会返回&#39; undefined&#39;无论。它收到的回复是一行,并且是&#34; application / json&#34;的内容类型。它有什么用? (不,它不是&#34; url在这里&#34;,我出于隐私原因删除了网址。如果有帮助,我可以提供。)

3 个答案:

答案 0 :(得分:0)

exports.get = function(key, app, vari) {

返回

    http.get('<url here>/?key='+key+'&app='+app+'&var='+vari+'&req=0', function (response) {
        response.setEncoding('utf8');
        response.on('data', function(body) {
            console.log(body);
            return body;
        });
    });
};

答案 1 :(得分:0)

reference,你需要听取结束事件并返回一个承诺,就像:

var exports = module.exports = {};
var http = require('http');

exports.get = function(key, app, vari) {
    return new Promise(function(resolve) {
        http.get('<url here>/?     key='+key+'&app='+app+'&var='+vari+'&req=0', function (response) {
      response.setEncoding('utf8');
      var data = '';
      response.on('data', function(chunk) {
          console.log(chunk);
          data += chunk;
      });
      response.on('end', function() {
          resolve(JSON.parse(data));
      });
  });
})

}

答案 2 :(得分:0)

我明白了,我只需要一个回答的电话。

&#13;
&#13;
var exports = module.exports = {};
var http = require('http');

exports.get = function(key, app, vari, answ) {
http.get('http://<url here>/?key='+key+'&app='+app+'&var='+vari+'&req=0', function (response) {
        response.setEncoding('utf8');
        response.on('data', function(body) {
            answ(body);
        });
    });
};
&#13;
&#13;
&#13;