我正在使用npm请求
进行节点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原型上调用call()时,我认为能够做的唯一事情就是控制台记录输出,我相信如果我使用数据库,我将能够插入它。我希望调用函数将结果的对象返回到调用它的位置(exports.startApiCall),因此我可以重新使用该函数,因为有时我想控制日志,有时使用它来构建不同的调用。
我试图从请求中返回正文,返回请求,它自己给了我一个没有身体的巨大对象。我还尝试将主体设置为变量并将其返回到函数的底部。然而,似乎注意到了。
提前致谢!
答案 0 :(得分: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
});
};