React笔记应用Express后端解构req.body时title显示undefined的错误解决请求
React笔记应用Express后端解构req.body时title显示undefined的错误解决请求
你遇到的这个TypeError: Cannot destructure property 'title' of 'req.body' as it is undefined错误,主要有两个关键原因,我帮你一步步排查解决:
1. 路由回调的参数顺序完全颠倒了
看你的路由代码第一行:
Router.put('/updateNote/:id', fetchuser, async (res, req) => {
Express路由的回调函数参数顺序是先请求对象req,后响应对象res,你现在把res放在了第一个位置,导致后面的req其实是响应对象,根本没有body属性,自然解构不出title、description这些字段。
修正后的路由开头应该是:
Router.put('/updateNote/:id', fetchuser, async (req, res) => {
2. 未配置Express的JSON请求体解析中间件
Express默认不会自动解析JSON格式的请求体,所以如果你的前端是发送JSON数据过来,后端必须在主入口文件(比如app.js/server.js)里添加如下中间件,才能把请求体解析到req.body中:
// 在引入路由之前添加这行代码 app.use(express.json());
修正后的完整路由代码
Router.put('/updateNote/:id', fetchuser, async (req, res) => { // create a new note object const { title, description, tag } = req.body; try { // Create a newNote object const newNote = {}; if (title) { newNote.title = title }; if (description) { newNote.description = description }; if (tag) { newNote.tag = tag }; // find the note to be updated let note = await Notes.findById(req.params.id); // case 1 ===> note is not present if (!note) { return res.status(404).send("Not Found") } if (note.user.toString() !== req.user.id) { return res.status(401).send("Not Allowed"); } note = await Notes.findByIdAndUpdate(req.params.id, { $set: newNote }, { new: true }) res.json({ note }); } catch (error) { console.error(error.message); res.status(500).send("Internal Server Error"); } })
另外再提醒你几个小细节:
- 确保前端发送请求时,请求头设置了
Content-Type: application/json,并且请求体是正确的JSON格式 - 测试接口时可以用Postman或者curl,先验证后端接口本身是否能正确接收参数
备注:内容来源于stack exchange,提问作者Basant Joshi
相关产品推荐
相关产品推荐

