nodejs web报废和回调问题

时间:2017-03-04 09:34:40

标签: javascript node.js express callback cheerio

我正在尝试删除网站上的某些内容,这一切都运行良好,但是我只能在控制台中为我提供报废文本,但我想在浏览器上打印这些报废数据。我认为我处理回调的方式有问题。有人可以帮忙吗?

我的代码如下:

new T()

1 个答案:

答案 0 :(得分:0)

从数据可用的回调函数发送响应。 请参阅以下代码:

app.get('/test', function(req, res) {

  //All the web scraping magic will happen here
  var url = 'https://www.mywebsite.com/path/to/abc';
  var allText;
  var getTheText = function() {
    request(url, function getText(error, response, html) {

      // First we'll check to make sure no errors occurred when making the request

      if (!error) {
        // Next, we'll utilize the cheerio library on the returned html which will essentially give us jQuery functionality

        var $ = cheerio.load(html);

        // Finally, we'll define the variables we're going to capture

        var allText = $('body')
          .children()
          .find('p')
          .text()

        console.log('allText');
        console.log(allText);
        // return allText;
        res.send(allText); // Send response from here
      } else {}

      //return result;
    });
    console.log(allText);

  }

  getTheText();
  console.log('gettheText is ' + getTheText());
  // res.send(allText); // Remove this line
})