Skip to content
Advertisement

How to display comments from a JSON server using javascript and HTML?

I am making this website project where people can leave comments and the webpage will dynamically display the comments without reloading the page. My comments are stored in an array in my server in the format Allcomments=[ { username: 'username', info: 'title', commentinfo: 'commentinfo ' }]. I am currently receiving this error when I try and run my code Uncaught (in promise) ReferenceError: res is not defined at main.js:53 at async loadComments (main.js:50) and the comments are not displaying as a result. I am also confused on how to implement the function so that it updates with new comments without needing a page reload. Any help or tips would be greatly appreciated! This is my code: index.html

<html>
<body>
<main>
  <div class="container">
    <hr>
    <h1>comments !</h1>
    <hr>
    <div class="row" id='commentsSection'></div>
  </div>
  </div>
</main>
<script src='client.js'></script>
</body>
</html>

client.js

async function GetComments () {
  let info = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json'
    },
  };
  await fetch('http://127.0.0.1:8090/comments', info)
    .then((res) => { return res.json(); })
    .then(data => {
      document.getElementById('commentsSection').innerHTML;
    }).then(() => {
      const comments = JSON.stringify(res);
      for (let comment of comments) {
        const y = `
          <div class="col-4">
              <div class="card-body">
                  <h5 class= "card-title">${comment.name}</h5>
                  <h6 class="card-subtitle mb-2 text-muted">${comment.info}</h6>
                  <div>comment: ${comment.comment}</div>
                  <hr>
              </div>
          </div>
      `;
        document.getElementById('commentsSection').innerHTML =
          document.getElementById('commentsSection').innerHTML + y;
      }
    });
}

GetComments();

server.js

const app = express();
const port = 8090;
const express = require('express')
const bodyParser = require('body-parser');
const cors = require('cors');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

let Allcomments=[];

app.get('/comments', (req, res) => {
    res.json(Allcomments);
});

Advertisement

Answer

You are using res in a .then block, but you didn’t pass it in from the earlier then block:

.then((res) => { return res.json(); }) // res is defined within this block only
.then(data => {
  document.getElementById('commentsSection').innerHTML;
.then(() => {
  const comments = JSON.stringify(res); // <- ReferenceError: res is not defined

This should fix it:

await fetch('http://127.0.0.1:8090/comment', info)

  // extract data from response body:
  .then((response) => { return response.json(); })

  // response body is comments array
  .then(comments => {
    for (let comment of comments) {
      const y = `
          <div class="col-4">
            <div class="card">
              <div class="card-body">
                  <h5 class= "card-title">${comment.name}</h5>
                  <h6 class="card-subtitle mb-2 text-muted">${comment.title}</h6>
                  <div>comment: ${comment.usercomment}</div>
                  <hr>
              </div>
             </div>
          </div>
      `;
      document.getElementById('commentsSection').innerHTML += y;
    }
  })

  // also add a catch block
  .catch(err => {
    console.error('error:', err)
  });

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement