Express.js博客应用POST请求体为何显示undefined?
问题:Express.js博客应用POST请求体undefined,表单提交后写入空对象
用Express.js构建简易博客应用时,遇到POST请求体req.body打印为undefined的问题:
console.log(req.body) // undefined
提交表单后,只会向blogs.json文件中添加空对象,已引入body-parser中间件但问题依旧。
相关代码
server.js
const express = require("express"); const bodyParser = require("body-parser"); const morgan = require("morgan"); const jsonfile = require("jsonfile"); const app = express(); const PORT = process.env.PORT || 3000; const file = "./db/blogs.json"; app.set("view engine", "ejs"); app.listen(PORT); app.use(bodyParser.json()); app.use(express.static("public")); app.use(morgan("dev")); app.get("/", async (req, res) => { try { const data = await jsonfile.readFile(file); res.render("index.ejs", { title: "Home", blogs: data }); } catch (err) { console.log(err); res.status(500).render("sr.ejs", { title: "Server Error" }); } }); app.get("/new", (req, res) => { res.render("new.ejs", { title: "Create New Blog" }); }); app.post("/new-blog/", async (req, res) => { // console.log(req.body) // undefined try { const blog = { title: req.body.title, author: req.body.author, content: req.body.content, }; const data = await jsonfile.readFile(file); data.push(blog); await jsonfile.writeFile(file, data); res.redirect("/"); } catch (err) { console.log(err); res.status(500).render("sr.ejs", { title: "Server Error" }); } }); app.get("/about", (req, res) => { res.render("about.ejs", { title: "About Us" }); }); app.use((req, res) => { res.render("nf.ejs", { title: "Page Not Found" }); }); process.on("uncaughtException", (err) => { console.log("UNCAUGHT ERROR:", err); process.exit(1); });
HTML表单代码
<main class="form-container"> <form action="/new-blog/" method="post"> <div> <label for="author">Author</label> <input id="author" name="author" type="text" placeholder="bobby8" required autocomplete="off" > </div> <div> <label for="title">Title</label> <input id="title" name="title" type="text" placeholder="My Favorite Movie" required autocomplete="off" > </div> <div> <label for="content">Content</label> <textarea id="content" name="content" type="text" placeholder="It has to be..." required autocomplete="off" ></textarea> </div> <button type="submit">Post Blog</button> </form> </main>
修复方案
1. 补充解析表单数据的中间件
你当前只配置了bodyParser.json()来解析JSON格式的请求体,但HTML表单默认发送的是application/x-www-form-urlencoded格式的数据,服务器无法解析该格式,导致req.body为undefined。
在app.use(bodyParser.json());后添加以下代码:
app.use(bodyParser.urlencoded({ extended: true }));
如果使用的是Express 4.16及以上版本,也可以直接用Express内置的解析器,无需依赖body-parser包:
app.use(express.json()); app.use(express.urlencoded({ extended: true }));
extended: true允许解析嵌套的表单数据,是更通用的配置。
2. 调整app.listen的位置(可选但规范)
将app.listen(PORT);移到所有中间件和路由配置的最后,这是Express应用的标准写法,避免可能的加载顺序问题:
// 放在文件末尾 app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });
修改后,服务器就能正确解析表单提交的数据,req.body将包含表单中的title、author和content字段,提交后会向blogs.json写入完整的博客对象。
内容的提问来源于stack exchange,提问作者k00
相关产品推荐
相关产品推荐

