Node.js无法从HTML表单推送数据至数组问题求助
问题修复:表单提交失败与数据不显示的解决方案
核心问题分析
- 表单提交按钮位置错误:你的
<button type="submit">写在了<form>标签外部,点击按钮无法触发表单的POST请求,后端/compose的POST路由从未被调用,输入内容根本没机会存入posts数组。 - 首页未传递posts数据:渲染
home模板时,没有把posts数组传给模板,即便数组有数据,页面也无法展示内容。
修复代码示例
1. 修正compose.ejs的表单结构
将提交按钮移入<form>标签内部:
<%- include("./partials/header"); -%> <br> <h1>Compose</h1> <form action="/compose" method="post"> <div class="form-group"> <label>Title</label> <input type="text" class="form-control" name="userTitle"> <label>Post</label> <textarea class="form-control" name="userPost" rows="5" cols="30"></textarea> </div> <!-- 按钮移至form内部 --> <br> <button type="submit" class="btn btn-secondary">Publish</button> </form> <%- include("./partials/footer"); -%>
2. 修改后端首页路由,传递posts数组
app.get("/", function(req, res){ // 将posts数组传入home模板 res.render("home", { startingContent: homeStartingContent, posts: posts }); console.log(posts); });
3. 补充home.ejs的内容渲染逻辑(如果未实现)
在首页模板中遍历posts数组展示内容:
<%- include("./partials/header"); -%> <h1><%= startingContent %></h1> <hr> <% posts.forEach(function(post){ %> <div class="post-item"> <h3><%= post.title %></h3> <p><%= post.posta %></p> </div> <% }) %> <%- include("./partials/footer"); -%>
修复后效果
点击Publish按钮后,表单会正确提交到后端,输入内容存入posts数组;重定向到首页后,模板会接收并渲染posts数据,控制台也会打印更新后的数组内容。
内容的提问来源于stack exchange,提问作者Indu Dwivedi
相关产品推荐
相关产品推荐

