如何使用 javascript 和 HTML 显示来自 JSON 服务器的评论?

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

我正在制作这个网站项目,人们可以在其中发表评论,网页将动态显示评论而无需重新加载页面。我的评论以 Allcomments=[ { username: 'username', info: 'title', commentinfo: 'commentinfo ' }] 格式存储在服务器的数组中。我目前在尝试 运行 我的代码 Uncaught (in promise) ReferenceError: res is not defined at main.js:53 at async loadComments (main.js:50) 时收到此错误,结果评论没有显示。我也对如何实现该功能感到困惑,以便它在不需要重新加载页面的情况下更新新评论。 任何帮助或提示将不胜感激!这是我的代码: 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);
});

在您的 main.js 文件中,删除第一个 then 语句中的 return 关键字。之后,循环数据数组并将数据附加到 HTML 元素中。

async function GetComments () {
  let options = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json'
    },
  };
  await fetch('http://127.0.0.1:3000/comment', options)
    .then(res => res.json())
    .then(data => {
      for (let comment of data) {
        const x = `
          <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 =
          document.getElementById('commentsSection').innerHTML + x;
      }
    });
}

GetComments();

您在 .then 块中使用了 res,但您没有从之前的 then 块中传入它:

.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

这应该可以解决问题:

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)
  });