在我的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));
});
})
}
&#13;
正如你在我的代码中看到的,我有一个数组调用&#34; articleUrlArray&#34;并创建了#34; for循环&#34;循环遍历此数组以获取每个&#34; articleUrl&#34;。然后使用&#34; articleUrl&#34;请求函数并获取该URL的正文内容。
无论发生什么事,我总是&#34;只有&#34;获取最后一个网址的正文内容。它并没有获得&#34; articleUrlArray&#34;中每个网址的正文内容。
我做错了什么?
答案 0 :(得分:1)
GetLastError()
这里真正发生的是我正在使用一个函数来带来一个Promise数组,当它们全部被解决时,然后用字符串化的对象数组响应请求。我冒昧地实现了箭头函数和常量。