2015-02-08 122 views
1

我使用NPM请求节点JS使用数据从请求/请求API调用返回

在这里使节点API调用一些基本的示例代码

request = require('request'); 

ApiRequest = function (options) { 
    this.uri = 'http://sampleapi.com/' + options.path, 
    this.method = options.method, 
    this.json = options.json 
}; 

ApiRequest.prototype.call = function() { 
    request(this, function (error, response, body) { 
     if (body) { 
      console.log(body); 
     } else { 
      console.log(error || "There was a problem placing your request") 
     } 
    }); 
}; 

exports.startApiCall = function() { 
    options = { 
     path: 'available', 
     method: 'GET' 
    }; 
    var myRequest = new Request(options); 
    myRequest.call(); 
}; 

当我在调用呼叫() ApiRequest原型唯一的想法,我似乎能够做的就像控制台登录输出,我相信如果我使用的数据库,我将能够插入它。我希望调用函数将结果的一个对象返回给从(exports.startApiCall)调用的地方,以便我可以重新使用该函数,因为有时我想要控制台记录它,有时使用它来构建不同的调用。

我试图从请求中返回正文,返回请求的自我给了我一个没有正文的巨大对象。我也尝试将body设置为一个变量,并将其返回到函数的底部。如何注意似乎正在工作。

在此先感谢!

+0

您将需要使用回调函数创建一个异步接口,该回调函数可以在操作完成时通知调用方以及结果是什么。您可以使用普通回调或承诺。 – jfriend00 2015-02-08 08:09:01

+0

你正在隐藏你的startApiCall中的请求变量...将它重命名为其他东西 - 'var r = new Request(options)' – lujcon 2015-02-08 08:10:34

+0

我试图让它成为一个回调函数,但我似乎无法将它返回,因为它只是返回了与身体无关的请求的值。我将如何执行promises @ jfriend00? – chrishillonline 2015-02-08 08:42:54

回答

0

您有可变的名称冲突。将你的本地请求变量重命名为别的东西。例如:

request = require('request'); 

Request = function (options) { 
    this.uri = 'http://sampleapi.com/' + options.path, 
    this.method = options.method, 
    this.json = options.json 
}; 

Request.prototype.call = function (callback) { 
    request(this, function (error, response, body) { 
     if (body) { 
      callback(error, body) 
     } else { 
      console.log(error || "There was a problem placing your request"); 
      callback(error); 
     } 
    }); 
}; 

exports.startApiCall = function (callback) { 
    options = { 
     path: 'available', 
     method: 'GET' 
    }; 
    var myRequest = new Request(options); 
    myRequest.call(function(error, body) { 
     //check the error and body here; 
     //do the logic 
     //you can also pass it through to the caller 
     callback && callback(error, body); 
    }); 
}; 

当你消耗你的模块(可以将其命名为mymodule),你可以这样做:

var my = require('mymodule'); 
my.startApiCall(function(error, body){ 
    //do something with body 
}); 

如果你不想让消费者有错误和/或身体直接,你可以玩删除回调参数:

exports.startApiCall = function() { 
    options = { 
     path: 'available', 
     method: 'GET' 
    }; 
    var myRequest = new Request(options); 
    myRequest.call(function(error, body) { 
     //check the error and body here; 
     //do the logic 
     //you can also pass it through to the caller 
    }); 
}; 
+0

我认为这个问题的主要观点是如何从请求中获得结果,而不是你没有解决的api调用函数。 – jfriend00 2015-02-08 08:26:55

+0

是的,我犯了一个小错误,因为我重命名了这些变量,使它们更具通用性,因为它们对于调用的内容非常具体。 – chrishillonline 2015-02-08 08:30:46

+0

你喜欢这种模式吗?如果没有 - 我可以为您提供基于承诺的解决方案。 – lujcon 2015-02-08 08:54:34