使用 Cheerio 和 Response for Node web scraper,将响应函数结果传递给视图

Using Cheerio and Response for Node web scraper, passing response function result to the view

我正在使用本教程: https://www.smashingmagazine.com/2015/04/web-scraping-with-nodejs/

制作一个真正基本的节点网络抓取工具。我已经设置了我的应用程序,运行在此处:

https://[redacted]/

它目前在我的节点应用程序的幕后正在做的事情是使用两个模块 cheerio 和请求 运行 这个功能(如下)。这个函数基本上接受一个 URL,发出请求并使用数据变量获取页面元素,抓取它的值,并将值(温度)记录到我计算机终端的控制台。我需要一种方法将此值发送到我的视图并将其呈现在页面上,而不是仅将其记录到我的计算机的控制台。

我遇到的问题是下面请求函数的范围,我无法将任何 return 值(温度)传递给我的视图。我知道我的设置有问题,因为我的 router.get 目前有请求函数 INSIDE。如果我将请求函数放在 router.get 之外,我仍然无法将值传递到我的视图,但它会成功地从 Web url 获取数据并将其记录到我的终端控制台。我希望我说得很清楚。请在我的视图中查看 res.render,它包装了正在执行网络抓取的请求函数..

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

    //target url we are scraping data from
    var url = "http://www.wunderground.com/cgi-bin/findweather/getForecast?&query=" + 02888;
    var temperature;
    // request function that uses the request module
    request(url, function (error, response, body) {

        if (!error) {
            // using cheerio module to load body of html req document and scrape the data
            var $ = cheerio.load(body),
                temperature = $("[data-variable='temperature'] .wx-value").html();
            // logs it to console (of my computer..)    
            console.log("It’s " + temperature + " degrees Fahrenheit.");
        } 

        else {
            console.log("We’ve encountered an error: " + error);
        }

        return temperature;
    });
    /* renders my view, this is my attempt to pass the values as variables to my handlebars template. Currently it is only passing the URL var as it exists before the request function call, and the empty var temperature (which gets its value during, and inside the request function call). How can i get at those values returned from the request function and pass to my view below? */
    res.render('index', {title: url, data: temperature } );  

});

request 中的函数是异步执行的,因此,如您所见,render 在设置温度之前被调用。您需要将 render 函数移动到异步函数中。

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

//target url we are scraping data from
var url = "http://www.wunderground.com/cgi-bin/findweather/getForecast?&query=" + 02888;
var temperature;
// request function that uses the request module
request(url, function (error, response, body) {

    if (!error) {
        // using cheerio module to load body of html req document and scrape the data
        var $ = cheerio.load(body),
            temperature = $("[data-variable='temperature'] .wx-value").html();
        // logs it to console (of my computer..)    
        console.log("It’s " + temperature + " degrees Fahrenheit.");
    } 

    else {
        console.log("We’ve encountered an error: " + error);
    }

    res.render('index', {title: url, data: temperature } );  
});

});