简体   繁体   中英

Send a response from a function to route in expressjs

I am trying to return JSON data from an api back along my route on an express server. I am a little confused about how nodejs handles this kind of operation. I have both a function and a route in the same file, the route works because I get the view returned, and the data I want in the console. The route and method look like this:

function getData() {
    request(url, function (error, response, body) {
        if (!error && response.statusCode == 200) {
          console.log(body) // Show the HTML for the Google homepage.
          return response.body; 
        };
    });
};

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index', { title: 'About', data: getData() });
});

I want the data from getData() in my response to the route. I thought this would do it but it will only print the data to the console and I can't see the problem.

That simply isn't possible due to the asynchronous nature of http requests. You'll have to instead restructure it to have a callback.

function getData(callback) {
    request(url, function (error, response, body) {
        if (error) {
            return callback(error);
        }
        if (response.statusCode == 200) {
          console.log(body) // Show the HTML for the Google homepage.
          //return response.body; 
          callback(null, response.body);
        } else {
            callback(response.statusCode);
        }
    });
};

/* GET home page. */
router.get('/', function(req, res, next) {
    getData(function (err, data) {
        if (err) {
            return next(err);
        }
        res.render('index', { title: 'About', data: data });
    });    
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM