Как сохранить состояние кеша из HTTP-запроса в nodejs? - PullRequest
0 голосов
/ 25 мая 2020

Ну, я посещаю массив URL-адресов, делая запрос для каждого из них, когда один запрос заканчивается, метод выполняет следующий. Массив выглядит примерно так: [ссылка1, ссылка2, ссылка3]. Если я попытаюсь сначала открыть ссылку 3 в браузере, я получу сообщение об ошибке (ошибка 404), но, открыв сначала ссылку 1 и ссылку 2, я получу желаемый ответ. В браузере работает без проблем, но в моем коде не работает, потому что по первым двум ссылкам я получил «status: 200», а по третьей - 404. (Если я открою ссылку 2 и ссылку 2 в браузере, проблема исчезнет, ​​но я хочу сделать это без использования браузера) Код:

function websiteOpener(links_array, index, final) {
var methodStr = className + '::websiteOpener';
try {
    log.info(methodStr + '>> Open the link: ' + links_array[index]);
    var protocol;
    var _host;
    var rawhost;
    if (links_array[index].match(/https:\/\/[^\/]+/)) {
        rawhost = links_array[index].match(/https:\/\/[^\/]+/);
        _host = rawhost[0].replace(/https:\/\//, '');
        protocol = 'https:'
        _path = links_array[index].replace(rawhost, '');
        incremental = index + 1;
        var options = {
            host: _host,
            path: _path,
            method: 'GET',
            headers: { 'Content-type': 'text/html' },
            protocol: protocol,
            agent: new https.Agent({
                rejectUnauthorized: false,
            })

        }
    } else {
        incremental = index + 1;
        var options =links_array[index];
    }

    if (incremental < final) {
        if (links_array[index].match(/https:\/\/[^\/]+/)) {
            var request = https.request(options, function (response) {
                console.log(response.statusCode);
                //if (response.statusCode === 200) {
                var data;
                response.on('data', (chunk) => {
                    data += chunk;
                });
                response.on('end', function () {
                    websiteOpener(links_array, incremental, final);
                });
                //}
            });

            request.end();
        } else {
            var request = http.request(options, function (response) {
                //if (response.statusCode === 200) {
                var data;
                response.on('data', (chunk) => {
                    data += chunk;
                });
                response.on('end', function () {
                    websiteOpener(links_array, incremental, final);
                });
                //}
            });
            request.end();
        }
    } else {

        options.headers = { 'Content-type': 'applcation/pdf' };
        var request = https.request(options, function (response) {
            console.log(response.statusCode);
            //if (response.statusCode === 200) {
            var data;
            response.on('data', (chunk) => {
                data += chunk;
            });
            response.on('end', function () {
                log.info(methodStr + '>>link found ' + links_array[index]);
            });
            //}
        });

        request.end();
    }
} catch (e) {
    log.error(methodStr + ">> Server error: ", e);
    reject({ statusCode: 500, flag: 'ERR_PROCESS' });
}

}

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