Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to get a page's HTML using fetch 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 empty string. Any guesses why it doesn't work?

question from:https://stackoverflow.com/questions/41921805/fetch-api-returning-an-empty-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
76 views
Welcome To Ask or Share your Answers For Others

1 Answer

I guess this might help, use as below:

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

And in server side, return content as plain text without setting header content-type.

I used $('#container') to represent the container that you want the html data to go after retrieving it.

The difference with fetching json data is using res.json() in place of res.text() And also, don't append any headers


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...