Подтвердить что ты не робот

Возврат HTML С помощью fetch()

Я пытаюсь извлечь файл и вернуть его HTML. Однако это не так просто, как я мог себе представить.

    fetch('/path/to/file')
    .then(function (response) {
      return response.body;
    })
    .then(function (body) {
      console.log(body);
    });

Это возвращает объект, называемый ReadableByteStream. Как использовать это для захвата содержимого HTML файла?

Если я изменю содержимое /path/to/file как строку JSON и изменим приведенное выше на:

    fetch('/path/to/file')
    .then(function (response) {
      return response.json();
    })
    .then(function (json) {
      console.log(json);
    });

... он правильно возвращает JSON. Как сделать выборку HTML?

4b9b3361

Ответ 1

Вам нужно использовать метод .text() вместо .json(). Это преобразует поток байтов в обычный текст, который может анализироваться браузером как HTML.

Ответ 2

Вы можете скачать html с помощью fetch, а затем проанализировать его с помощью API DomParser.

fetch('somePage.html')
    .then(function(response) {
        // When the page is loaded convert it to text
        return response.text()
    })
    .then(function(html) {
        // Initialize the DOM parser
        var parser = new DOMParser();

        // Parse the text
        var doc = parser.parseFromString(html, "text/html");

        // You can now even select part of that html as you would in the regular DOM 
        // Example:
        // var docArticle = doc.querySelector('article').innerHTML;

        console.log(doc);
    })
    .catch(function(err) {  
        console.log('Failed to fetch page: ', err);  
    });

Ответ 3

Должно быть:

fetch('/path/to/file').then(function(response) {
    return response.text();
}).then(function(string) {
    console.log(string);
}).catch(function(err) {  
    console.log('Fetch Error', err);  
});