Handlebars.js+Express.js:帖子下评论无法正常显示求助
问题排查:Express+Handlebars评论无法显示
我正在开发一款支持用户发布帖子及评论的Web应用,前端采用Handlebars.js渲染,后端基于Express.js搭建。目前遇到帖子下评论无法正常显示的问题:已确认服务器可成功获取并打印评论数据,Handlebars模板配置无误,但评论仍未按预期展示在对应帖子下方。我已排查数据获取流程、客户端JavaScript代码、Handlebars模板、CSS样式及服务器日志,仍未定位到问题根源。
相关代码
commentRoutes.js
router.get('/', async (req, res) => { try { const commentData = await Comment.findAll({ attributes: ['id', 'comment_text', 'user_id', 'post_id', 'created_at'], order: [['created_at', 'DESC']], include: [ { model: User, attributes: ['username'], }, ], }); console.log('Comments Data:', commentData); res.status(200).json(commentData); } catch (error) { console.log(error); res.status(500).json({ error }); } });
comments.handlebars
{{log post}} <div class="comments"> {{#each this}} <div class="comment"> <p>{{user.username}} on {{format_date created_at}}</p> <div class="text">{{comment_text}}</div> </div> {{/each}} </div>
post.handlebars
{{> post-info post}} {{#if loggedIn}} <form class="comment-form"> <div class="comment-container"> <label for="comment-body">Leave a comment:</label> <textarea name="comment-body"></textarea> <button class="button add-comment-btn" type="submit">Add Comment</button> </div> </form> {{/if}} {{> comments post.comments}} {{#if loggedIn}} <script src="/js/comment.js"></script> {{/if}}
comment.js
const commentFormHandler = async function (event) { event.preventDefault(); // Extract post_id from the current URL const post_id = window.location.toString().split('/')[ window.location.toString().split('/').length - 1 ]; // Get comment text from the textarea const comment_text = document .querySelector('textarea[name="comment-body"]') .value.trim(); // Check if comment text is not empty if (comment_text) { try { // Send a POST request to create a new comment const response = await fetch('/api/comments', { method: 'POST', body: JSON.stringify({ post_id, comment_text, }), headers: { 'Content-Type': 'application/json', }, }); // Check if the response is successful if (response.ok) { // Reload the page to display the new comment document.location.reload(); console.log('Comment created successfully!'); } else { // Display an alert with the error message if unsuccessful alert('Failed to create comment'); } } catch (error) { // Log any unexpected errors to the console console.error('Error creating comment:', error); // Display an alert for unexpected errors alert('Failed to create comment'); } } }; // Attach the commentFormHandler to the button's click event document .querySelector('.add-comment-btn') .addEventListener('click', commentFormHandler);
核心排查方向
1. 帖子详情路由未关联当前帖子的评论数据
当前commentRoutes.js的GET接口是获取所有评论,但帖子详情页需要的是当前帖子对应的评论。检查帖子详情路由(如/api/posts/:id)是否在查询Post时,通过include关联Comment模型,将评论数据注入到post.comments中。
示例修正代码:
router.get('/:id', async (req, res) => { try { const postData = await Post.findByPk(req.params.id, { include: [ { model: User, attributes: ['username'] }, { model: Comment, include: [{ model: User, attributes: ['username'] }] } ] }); const post = postData.get({ plain: true }); res.render('post', { post, loggedIn: req.session.loggedIn }); } catch (err) { res.status(500).json(err); } });
2. Handlebars模板变量与数据结构不匹配
- 检查
comments.handlebars中,评论关联的用户字段是否为user:如果模型关联时使用了别名(如as: 'User'),则需改为{{User.username}}。 - 确认自定义助手
format_date已在Express中注册,未注册会导致模板渲染失败,可能隐藏评论内容。 - 可以在模板中添加空状态提示,验证
post.comments是否为空数组:<div class="comments"> {{#if this.length}} {{#each this}} <div class="comment"> <p>{{user.username}} on {{format_date created_at}}</p> <div class="text">{{comment_text}}</div> </div> {{/each}} {{else}} <p>还没有评论,快来抢沙发!</p> {{/if}} </div>
3. 评论创建后的数据库关联验证
检查POST评论接口是否正确将post_id存入数据库,确保新创建的评论与当前帖子关联。可以通过数据库查询确认评论的post_id字段是否匹配当前帖子ID。
内容的提问来源于stack exchange,提问作者Eric Risher
相关产品推荐
相关产品推荐

