无法使用Body Parser获取表单输入值,请求技术排查与解决
问题分析与解决方案
核心问题
你的Express服务器代码中,/compose的POST路由回调函数参数顺序写反了:
app.post("/compose",(res,req)=>{ console.log(req.body.postTitle); })
这里第一个参数必须是请求对象req,第二个是响应对象res,顺序颠倒后,req实际是响应对象,根本无法获取req.body里的表单数据。
完整修正方案
1. 修正服务器代码
调整参数顺序,同时添加博客数据存储和页面渲染逻辑:
const express = require("express"); const path = require("path"); const bodyParser = require("body-parser") const app = express(); // 用于存储博客数据的数组 let posts = []; app.set("view engine", "ejs"); app.set("views", path.join(__dirname, "views")); app.use(bodyParser.urlencoded({extended:true})) app.get("/",(req,res) =>{ // 将博客数据传递给主页模板 res.render("mainpage", { posts: posts }); }) app.get("/compose",(req,res) =>{ res.render("compose") }) // 修正参数顺序:req在前,res在后 app.post("/compose",(req,res)=>{ // 提取表单中的标题和内容 const newPost = { title: req.body.postTitle, content: req.body.blogtext }; // 保存到数组中 posts.push(newPost); // 重定向到主页查看新博客 res.redirect("/"); }) app.listen(3000,()=> console.log('server started on port 3000'));
2. 修改主页(mainpage.ejs)渲染博客数据
在mainpage.ejs中添加循环渲染逻辑,示例如下:
<%- include("partials/header"); -%> <h1>我的博客</h1> <% posts.forEach(post => { %> <div class="card mt-3"> <div class="card-body"> <h5 class="card-title"><%= post.title %></h5> <p class="card-text"><%= post.content %></p> </div> </div> <% }) %> <%- include("partials/footer"); -%>
验证步骤
- 重启Express服务器
- 访问
http://localhost:3000/compose,填写博客标题和内容并提交 - 页面会重定向到主页,你能看到刚发布的博客内容
内容的提问来源于stack exchange,提问作者Arsh Meharwal
相关产品推荐
相关产品推荐

