【问题标题】:How to display comments from a JSON server using javascript and HTML?如何使用 javascript 和 HTML 显示来自 JSON 服务器的评论?
【发布时间】:2021-04-05 17:31:45
【问题描述】:

我正在制作这个网站项目,人们可以离开 cmets,网页将动态显示 cmets 而无需重新加载页面。我的 cmets 以 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) 时,我目前收到此错误,结果 cmets 未显示。我也对如何实现该功能感到困惑,以便在不需要重新加载页面的情况下使用新的 cmets 进行更新。 任何帮助或提示将不胜感激!这是我的代码: 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);
});

【问题讨论】:

    标签: javascript node.js json rest client-server


    【解决方案1】:

    您在 .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)
      });
    
    

    【讨论】:

    • 为什么我需要在我的 HTML 中将 res 传递给 cmetsSection?这就是我想要放置动态代码的区域
    • @userj 您需要将comments 传递给 cmets 块,comments 只是响应正文。请参阅上面的代码,我刚刚对其进行了简化。 (您的代码在 cmets 块中引用了res,它没有被定义,这导致了您提到的错误)
    【解决方案2】:

    在您的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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-28
      • 2016-04-29
      • 2019-12-07
      • 1970-01-01
      • 1970-01-01
      • 2020-09-05
      • 1970-01-01
      • 2014-07-19
      相关资源
      最近更新 更多