'How to get a nice dispay after fetch?

I am experimenting with fetch in some web page, in order to use it in a project. And I have an issue I need to solve.

The code is below, I use a fetch to access my site (https://mynicewebsite.example.com), possibly setting some options (headers ....)... By using document.getElementById('bdyID').innerHTML = await response.text(); I display the contents of the site (https://mynicewebsite.example.com) in the browser. But this way of doing shows the whole text as a long continuous character string. How can I get a nice HTML display showing the site as it usually appears in a browser when someone directly goes to visit it.

Here the code:

<!DOCTYPE html>
<html>
<head>
</head>
<body id='bdyID'>
<script>
   const makeFetchCall = async () => {
      const response = await fetch('https://mynicewebsite.example.com', {
         method: 'GET',
         headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer blahfblahdblahzblah',
            //..... // possibly some other things
         }
      });

      document.getElementById('bdyID').innerHTML = await response.text();
   }

   makeFetchCall();
</script>
</body>
</html>

Here is a screenshot of the display with the code above:

enter image description here

And here is a screenshot of the display when looking directly at https://mynicewebsite.example.com in the browser:

enter image description here



Solution 1:[1]

I suppose by the content-type header that you can call .json on the response object.

const data = await response.json()
const formattedResponse = JSON.stringify(data, null, 2);
document.getElementById('bdyID').innerHTML = formattedResponse;

JSON.stringify take three params. the third param is space https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Be aware that you can see your response in the devtools well formatted anyway. Example with json and pre tag: https://codesandbox.io/s/condescending-platform-f6gj6?fontsize=14&hidenavigation=1&theme=dark

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1