使用JavaScript、AJAX与Node.js时POST请求后端取值为undefined问题
问题解决:Node.js服务端无法获取POST请求的JSON数据
你的问题根源是前端POST请求没设置正确的请求头,导致express的express.json()中间件无法解析请求体,所以req.body.title才会返回undefined。
修改方法:给fetch请求添加请求头
前端的fetch调用里,必须加上Content-Type: application/json头,告诉服务端请求体是JSON格式。修改后的前端代码如下:
async function saveUsercategories(displayElement, userId) { const comment = { title: "HELLO", text: "How are you?"}; await fetch(`/admin-usercategories/${userId}/edit`, { method: 'POST', headers: { 'Content-Type': 'application/json' // 新增请求头配置 }, body: JSON.stringify(comment) }); }
验证后端配置
你的后端代码已经正确配置了express.json()中间件,这部分无需修改:
app.use(express.json()); app.post("/admin-usercategories/:id/edit", async function (req, res) { try { console.log('Title - ' + req.body.title); res.json({message: 'Insertion completed!'}) } catch (error) { res.status(500).json(error); } })
修改后重新测试,服务端就能正常拿到req.body.title的值了。
内容的提问来源于stack exchange,提问作者kbdev
相关产品推荐
相关产品推荐

