Ax ios url get request для html ответа 200, но response.data пуст - PullRequest
0 голосов
/ 07 апреля 2020

Так что я использую этот URL, потому что я так хочу почистить html, используя топор ios и cheerio: https://www.mgewholesale.com/ecommerce/Bags%20and%20Cases.cfm?cat_id=876

Я протестировал запрос get в почтальоне, и он работает нормально со статусом 200

, используя этот код, также работает со статусом 200, но response.data пусто

update, поэтому с этим кодом я получил фактический ответ с заполненным объектом данных, но Когда я пытаюсь получить доступ к response.data, он показывает мне эту ошибку:

const axios = require('axios'); 
const cheerio = require('cheerio');
const https = require('https');

let fs = require('fs');

const httpsAgent = new https.Agent({ keepAlive: true });

axios
    .get('https://www.mgewholesale.com/ecommerce/Bags%20and%20Cases.cfm', {
        httpsAgent,
        params: {
            cat_id: '876',
        },
        headers: {
            'Accept-Encoding': 'gzip, deflate, br',
        },
        //is the same as set the entire url
    })
    .then((res) => {

        console.log(res.data)
        //this triggers the error

       // let status = res.status;
        console.log(status);
       //Status 200
       console.log(response)
        //This brings the entire response with data object filled

    });

ERROR:
(node:9068) UnhandledPromiseRejectionWarning: Error: read ECONNRESET
    at TLSWrap.onStreamRead (internal/stream_base_commons.js:205:27)
(node:9068) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:9068) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Я пытался использовать весь URL-адрес и URL-адрес с его параметрами, он приносит мне пустые данные, но если я пытаюсь с другим URL-адресом, как : https://www.google.com это приносит мне фактический html.

1 Ответ

2 голосов
/ 07 апреля 2020

Проблема в том, что параметры вашего запроса не добавляются правильно.

Удалите + '.json' из второго аргумента axios.get.

Я удивлен, что это не так выдает ошибку самостоятельно, но очевидно, что ax ios просто подыгрывает и добавляет 0=[object+Object].json, превращая ваш URL в: https://www.mgewholesale.com/ecommerce/Bags%20and%20Cases.cfm?0=[object+Object].json

Я не могу добавить комментарий к другому ответу, но это неверно, поскольку вы правильно используете цепочку обещаний (.then) после вызова .get().


Редактировать:
Похоже, что для этого конкретного URL вам понадобятся дополнительные заголовки, а также возможность поддерживать соединение после первоначального ответа:

const axios = require('axios'); //15k (gzipped: 5.1k)
const cheerio = require('cheerio');
const https = require('https');

let fs = require('fs');

const httpsAgent = new https.Agent({ keepAlive: true });

axios
    .get('https://www.mgewholesale.com/ecommerce/Bags%20and%20Cases.cfm', {
        httpsAgent,
        params: {
            cat_id: '876',
        },
        headers: {
            'Accept-Encoding': 'gzip, deflate, br',
        },
        //is the same as set the entire url
    })
    .then((res) => {
        let status = res.status;
        console.log(status);
        //This should now output the html content
        console.log(res.data);
    })
    .catch(err => console.error(err));

Редактировать 2:
В приведенный выше код добавлен правильный метод обработки ошибок.

Редактировать 3:
Убедитесь, что все переменные, которые вы регистрируете в своем блоке .then(), определены. Кроме того, чтобы получить больше полезных ошибок, добавьте .catch() в конце:

    .then((res) => {
        console.log(res.data);
        //this triggers the error

        let status = res.status;
        console.log(status);
        //Status 200
        console.log(res);
        //This brings the entire response with data object filled
    })
    .catch(err => console.error(err));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...