Fetch API for HTML response

I am trying to get HTML pages using the API. Here is my code.

var quizUrl = 'http://www.lipsum.com/';
var myHeaders = new Headers();
myHeaders.append('Content-Type', 'text/html');
fetch(quizUrl,{
    mode: 'no-cors',
    method: 'get',
    headers: myHeaders
}).then(function(response) {
    response.text().then(function(text) {
        console.log(text);
    })
}).catch(function(err) {
  console.log(err)
});

It returns an empty string. Any guesses why this is not working?

+6
source share
2 answers

Oh (from MDN, emphasis mine)Request.mode 'no-cors'

, HEAD, GET POST. - ServiceWorkers , , . , JavaScript - Response.. , ServiceWorkers , - .

, , Response opaque, , , , .

, , -.


PS: , , :

var quizUrl = 'http://www.lipsum.com/';
fetch(quizUrl, {
  mode: 'no-cors',
  method: 'get'
}).then(function(response) {
  console.log(response.type)
}).catch(function(err) {
  console.log(err) // this won't trigger because there is no actual error
});
+6

, , , :

fetch('/url/to/get/html/file')
.then((res) => {
      return res.text();
})
.then((data) => {
     $('#container').html(data);
}

$('#container') , html-, .

json- res.json()  res.text()

+5

Source: https://habr.com/ru/post/1014535/


All Articles