【发布时间】: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