NodeJS新手使用POST请求向MongoDB存博客遇TypeError错误求助
解决TypeError: Cannot read properties of undefined (reading 'title')错误
这个错误的核心原因是你没有配置Express的请求体解析中间件,导致req.body是undefined,自然无法读取req.body.title这类属性。
修复步骤:
- 在你的Express应用中,添加请求体解析中间件,处理JSON格式的POST数据:
在app.post("/blogs", ...)之前插入以下代码:app.use(express.json()); - 如果你的POST请求是表单提交的
x-www-form-urlencoded格式,还需要额外添加:app.use(express.urlencoded({ extended: true }));
修改后的完整代码示例:
const express = require("express") const app = express() const mongoose = require("mongoose") const Schema = mongoose.Schema; // 添加请求体解析中间件 app.use(express.json()); // 若需处理表单数据,取消下面注释 // app.use(express.urlencoded({ extended: true })); const BlogPost = new Schema({ title:{ type: String, required: true }, content: { type: String, required: true }, body: { type: String, required: true } }) const Blog = mongoose.model("Blog", BlogPost) module.exports = Blog; app.post("/blogs", (req, res) => { const blogs = new Blog({ title: req.body.title, content: req.body.content, body: req.body.body, }) blogs.save() .then(result => { console.log(result) res.status(201).send(result) // 建议添加响应,避免请求挂起 }) .catch(err => { console.log(err) res.status(400).send(err) // 错误时也返回响应 }) }) // 记得添加启动服务器的代码 app.listen(3000, () => console.log("Server running on port 3000"))
另外补充两点:
- 原代码缺少启动服务器的逻辑,必须加上
app.listen()才能让服务运行起来接收请求。 - 在
save()的回调里建议给客户端返回HTTP响应,避免客户端请求一直处于挂起状态。
内容的提问来源于stack exchange,提问作者Emmanuel uzoezie
相关产品推荐
相关产品推荐

