Node.js & Express: Как создать много вызовов app.get с помощью Express.js через цикл for? - PullRequest
0 голосов
/ 20 мая 2018

В моем файле server.js я пытаюсь перебрать массив, который имеет разные URL-адреса, и использую эти URL-адреса для функции запроса app.get.

Вот мой код:

let articleUrlArray = [ 'https://techcrunch.com/2018/05/19/shared-housing-startups-are-taking-off/',
  'https://techcrunch.com/2018/05/19/shared-housing-startups-are-taking-off/',
  'https://techcrunch.com/2018/05/19/my-data-request-lists-guides-to-get-data-about-you/',
  'https://techcrunch.com/2018/05/19/siempos-new-app-will-break-your-smartphone-addiction/',
  'https://techcrunch.com/2018/05/19/la-belle-vie-wants-to-compete-with-amazon-prime-now-in-paris/',
  'https://techcrunch.com/2018/05/19/apple-started-paying-15-billion-european-tax-fine/',
  'https://techcrunch.com/2018/05/19/original-content-dear-white-people/',
  'https://techcrunch.com/2018/05/19/meet-the-judges-for-the-tc-startup-battlefield-europe-at-vivatech/',
  'https://techcrunch.com/2018/05/18/nasas-newest-planet-hunting-satellite-takes-a-stellar-first-test-image/',
  'https://techcrunch.com/video-article/turning-your-toys-into-robots-with-circuit-cubes/',
  'https://techcrunch.com/2018/05/18/does-googles-duplex-violate-two-party-consent-laws/' ];

for(var i = 0; i < articleUrlArray.length-1; i++) {
  app.get('/news/news-desc', function(req, res) {

    var data = '';
    
    var techCrunchNewsItems = [];

    request( articleUrlArray[i], function(err, response, html) {
      var $ = cheerio.load(html);

      if($('.article-content').children('p').eq(0).text().split(' ').length > 50) {

        techCrunchNewsItems.push({
          bodyOne: $('.article-content').children('p').eq(0).text()
        });
      } else {

        techCrunchNewsItems.push({
          bodyOne: $('.article-content').children('p').eq(0).text(),
          bodyTwo: $('.article-content').children('p').eq(1).text()
        });
      }
        
      data = techCrunchNewsItems;

      res.send(JSON.stringify(data));
    });
  })
}

Как вы можете видеть в моем коде, у меня есть вызов массива "articleUrlArray" и я создал "for loop", чтобы пройти через этот массив, чтобы получить каждый "articleUrl".Затем используйте этот «articleUrl» для функции запроса и получите содержимое тела для этого URL.

Независимо от того, что произойдет, я всегда «только» получаю содержимое тела для последнего URL.Он не получает содержимое тела для всех URL-адресов в "articleUrlArray".

Что я делаю не так?

Вот скриншот того, что я получаю после запуска решения Уго Наскиутти ниже:enter image description here

1 Ответ

0 голосов
/ 20 мая 2018
const articleUrlArray = [
    'https://techcrunch.com/2018/05/19/shared-housing-startups-are-taking-off/',
    'https://techcrunch.com/2018/05/19/shared-housing-startups-are-taking-off/',
    'https://techcrunch.com/2018/05/19/my-data-request-lists-guides-to-get-data-about-you/',
    'https://techcrunch.com/2018/05/19/siempos-new-app-will-break-your-smartphone-addiction/',
    'https://techcrunch.com/2018/05/19/la-belle-vie-wants-to-compete-with-amazon-prime-now-in-paris/',
    'https://techcrunch.com/2018/05/19/apple-started-paying-15-billion-european-tax-fine/',
    'https://techcrunch.com/2018/05/19/original-content-dear-white-people/',
    'https://techcrunch.com/2018/05/19/meet-the-judges-for-the-tc-startup-battlefield-europe-at-vivatech/',
    'https://techcrunch.com/2018/05/18/nasas-newest-planet-hunting-satellite-takes-a-stellar-first-test-image/',
    'https://techcrunch.com/video-article/turning-your-toys-into-robots-with-circuit-cubes/',
    'https://techcrunch.com/2018/05/18/does-googles-duplex-violate-two-party-consent-laws/'
];

const checkBody = res => (err, response, html) => {
    const $ = cheerio.load(html);
    const articleContent = $('.article-content').children('p')
    const bodyOne = articleContent.eq(0).text()
    const bodyTwo = articleContent.eq(1).text()
    const isExtensive = bodyOne.split(' ').length > 50
    res(isExtensive ? { bodyOne } : { bodyOne, bodyTwo })
}

const getArticle = article => new Promise(res => request(article, checkBody(res)))

app.get('/news/news-desc', (req, res) => {
    Promise.all(articleUrlArray.map(getArticle)).then(data => res.send(JSON.stringify(data)))
})

На самом деле здесь происходит то, что я использую функцию, чтобы вывести массив Обещаний, и когда все они решаются, тогда отвечаю на запрос с массивом объектов в строковом виде.Я взял на себя смелость реализовать функции и константы со стрелками.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...