#javascript #node.js #json #rest #client-server
#javascript #node.js #json #остальное #клиент-сервер
Вопрос:
Я создаю этот веб-проект, в котором люди могут оставлять комментарии, а веб-страница будет динамически отображать комментарии без перезагрузки страницы. Мои комментарии хранятся в массиве на моем сервере в формате 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);
});
Ответ №1:
Вы используете res в .then
блоке, но вы не передали его из предыдущего 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)
});
Комментарии:
1. зачем мне нужно передавать res в раздел commentsSection в моем HTML? это как раз та область, в которой я хочу разместить динамический код
2. @userj Вам нужно перейти в
comments
блок комментариев, иcomments
это просто тело ответа. Смотрите приведенный выше код, который я только что упростил. (Ваш код ссылалсяres
в блоке комментариев, где он не был определен, что вызывало упомянутую вами ошибку)
Ответ №2:
В вашем main.js
файле удалите return
ключевое слово в первом then
операторе. После этого выполните цикл массива данных и добавьте данные в 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();