Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fetch API returning an empty string

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?

like image 524
Pankaj Phartiyal Avatar asked Jan 29 '17 14:01

Pankaj Phartiyal


People also ask

What does the fetch API return?

The Fetch API allows you to asynchronously request for a resource. Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.

Does fetch return a value?

The fetch() method returns a promise that can either be resolved or not. Thus, this method always returns a value and the only possible case where it may fail to return anything is a server error.

How do I get API response in HTML?

The trick is to use the text() method instead of the json() method on the stream. This will return a text string of the HTML. fetch('/about'). then(function (response) { // The API call was successful!


1 Answers

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

like image 126
Danny Sofftie Avatar answered Oct 07 '22 02:10

Danny Sofftie