Momu
Momu

Reputation: 33

displaying api response on html page

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>JSON Test</title>
</head>
<body>
   <h1>Hello World</h1>
   <div id="myData"></div>
   <script>
       fetch('http://localhost:3000/api/product/1234567')
           .then(function (response) {
               return response.json();
           })
           .then(function (data) {
               appendData(data);
           })
           .catch(function (err) {
               console.log('error: ' + err);
           });
       function appendData(data) {
           console.log(data)
           var mainContainer = document.getElementById("myData");
           for (let key in data) {
               var div = document.createElement("div");
               div.innerHTML = 'name: ' + data[key] + 'label' + data[key];
               mainContainer.appendChild(div);
           }
       }
   </script>
</body>
</html>

Trying to fetch the json response and display it on html page. It's giving me an error: SyntaxError: Unexpected end of JSON input. I guess I'm here to maybe get some help on how to fix this and why this is happening. Thank you.

edit:

The response I get on my console :

{ product: 1234567, name: 'TV', salePrice: 149.99 }

Upvotes: 0

Views: 814

Answers (1)

Ritesh Tiwari
Ritesh Tiwari

Reputation: 30

The major reason is your response is not in the JSON format, which could be because of getting some non-json format response. Please post the sample JSON response format to understand better.

Upvotes: 1

Related Questions