0
Hello I have a problem here, I need to use the Node request module, twice. one to take the link from one page and the other to take the content of a post.
in this way, I have the following problem:
request('https://www.pensarcontemporaneo.com/, function (error, response, body) {
if (!error && response.statusCode == 200) {
const $ = cheerio.load(body);
// na página inicial ele vai pegar o link de uma postagem recente...
const href = $('.td_block_inner').find('.td-module-thumb').children().first().attr('href');
// aqui ele vai entrar neste link pra pegar o conteúdo da postagem
request(href, function (error2, response2, body2) {
const $2 = cheerio.load(body);
// preste atenção, eu preciso que essa variavel vá para dentro da array article
var content = $2('.td-ss-main-content').html();
console.log(content); // aparece o conteúdo
});
var article = {
// só que aqui ele chega vazio
content: content,
link: href,
thumb: $('.td_block_inner').find('img').first().attr('src'),
title: $('.td_block_inner').find('.entry-title').children().first().text(),
}
}
});
I come from php so I don’t have much experience with javascript, let alone Node, to very disoriented.
The declaration of the variable
article
must be inside the callback of the second request. How therequest
is asynchronous, it will run the rest of the code (var article = { ... }
) before the request is even completed and you have the value ofcontent
. Another thing, the variablecontent
(in the second request) it is local and will not be visible outside this function.– Valdeir Psr
What you can do is use Promise or https://github.com/ForbesLindesay/sync-request
– Valdeir Psr
Valdeir thanks, I put the article inside the second request, as I didn’t think of it before, thanks bro ;)
– Ramon Saldanha