节点 js 使用 request/request api 调用返回的数据

Node js using data returned from request/request api call

我正在使用 npm request

进行节点 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() 时,我唯一认为我能做的就是控制台记录输出,我确信如果我使用的是数据库,我将能够插入它。我希望调用函数 return 我的结果对象到它被调用的地方( exports.startApiCall )所以我可以重新使用该函数,因为有时我想控制台记录它,有时用它来建立一个不同的电话。

我已经尝试 return 请求的正文,return 请求本身给了我一个没有正文的巨大对象。我还尝试将 body 设置为一个变量,并将其 return 设置在函数的底部。注意到似乎是如何工作的。

提前致谢!

您有变量名冲突。将您的本地请求变量重命名为其他名称。例如:

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
});

如果您不希望消费者直接玩错误 and/or 正文,您可以删除回调参数:

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
    });
};