首页 > 解决方案 > node js爬虫和expresse

问题描述

我想知道如何在使用 npm crawler 爬行后发送结果。我收到了这个错误

错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头

有什么帮助吗?

app.get('/', async (req, result) => {
    var c = new Crawler({
        maxConnections: 10,
        callback: function(error, res, done) {
            if (error) {
                console.log(error);
            } else

            {
                var $ = res.$;
                $('.ajax_block_product').each(function(i, elem) {
                    var x = $(elem)
                    produit.site = x.find('a').attr('href').split('w.').pop().split('.tn')[0];
                    produit.image = x.find('img').attr('src');
                    produit.lien = x.find('a').attr('href');
                    produit.Nom_produit = x.find('a').attr('title');
                    produit.Prix = x.find('span.price').text();
                    produit.Etat = x.find('span.available-now').text();
                    produits.push(produit);

                });
                $('.item-product').each(function(i, elem) {
                    var x = $(elem)
                    produit.site = x.find('a').attr('href').split('w.').pop().split('.tn')[0];
                    produit.image = x.find('img').attr('src');
                    produit.lien = x.find('a').attr('href');
                    produit.Nom_produit = $(x.find('a')).find('p').text().substr(0, 27);
                    produit.Prix = x.find('span.price').text();
                    produit.Etat = x.find('span.available-now').text();
                    produits.push(produit);


                });
                console.log(produits)
                result.send(produits)
            }
            done();

        },
    })

    c.queue([url1, url2, url3, url4])

})

标签: node.jsweb-crawler

解决方案


您可以将标题设置res.headers({})为对象,您可以在此处找到更多信息:https ://www.npmjs.com/package/crawler#callbacks 。

另外,我建议您在else范围内设置代码,这样它只会在没有错误时运行代码。

为了消除另一个错误来源,您可能想要丢弃您在第 1 行中使用的 REST API app.get,我只需通过在本地调用它来测试它来正常运行该命令。


推荐阅读