Unable to return body of request method in nodejs

佐手、 提交于 2021-01-28 06:11:36

问题


I'm trying to get a JSON response via the request method and return the output so that i can store it in a variable when the function is called. when i log the response within the request method, it works fine. However when i return the output, it doesn't return.

 var getAPIresponse = function(url) {
    var request = require('request');
    request(url, function(error, response, body) {
        if(!error && response.statusCode == 200) {
            console.log(body); // WORKS PERFECTLY
            return body;      // I Believe the issue is here
        } else {
            console.log("Error: "+ error);
        }
    });
};

router.get('/', function (req, res) {
    var poolList =  getAPIresponse("www.addAURL");

    console.log(poolList); // DOESN'T WORK. REPORTS AS UNDEFINED
    res.render('index', model); // THIS IS JUST SAYS HELLO WORLD
});

回答1:


What your method actually does is run the following two lines

var request = require('request');
request(url, function(error, response, body) {

...and then fall out of the function right away at which point your calling code gets undefined back. The callback isn't called until the request is done, which may be much later.

To make it work, your function needs a callback too that is called when the function is actually complete, something like;

var getAPIresponse = function(url, cb) {
    var request = require('request');
    request(url, function(error, response, body) {
        if(!error && response.statusCode == 200) {
            console.log(body); // WORKS PERFECTLY
        } else {
            console.log("Error: "+ error);
        }
        cb(error, body);
    });
};

router.get('/', function (req, res) {

    var poolList =  getAPIresponse("www.addAURL", function(err, poolList) {

        // This is run in a callback once the request is done.    
        console.log(poolList);
        res.render('index', model);

    });
});

Another way would be to use promises which can clean up the code somewhat when the number of callbacks is getting out of hand.



来源:https://stackoverflow.com/questions/35618940/unable-to-return-body-of-request-method-in-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!