为何我的fetch PUT请求服务器端req.body返回undefined?
问题
我使用带PUT方法的fetch请求并传入body,但调用服务器端定义的接口时,req.body始终返回undefined。有人知道原因吗?
前端请求代码:
<tr> <td><%= index %></td> <td class="editable" id="item"> <%= item %> </td> <td class="editable" id="desc"> <%= desc %> </td> <td class="editable" id="status"> <%= status %> </td> <td class="editable" id="priority"> <%= priority %> </td> <td><button id="delete-button">Delete</button> <button onclick="refetch(this)">Edit</button> </td> </tr> <script> async function refetch(btn) { if (btn.innerHTML === 'Edit') { await fetch('http://localhost:3000/todo', { method: 'PUT', body: { edit: 'true' } }) } } </script>
服务器端接口代码:
app.put("/todo", (req, res) => { console.log(req.body); });
解决方法
问题出在两个核心环节,一一修正即可:
1. 前端请求未正确格式化请求体
Fetch API不会自动将JavaScript对象转换为服务器可解析的格式,直接传对象的话,浏览器会把它序列化为[object Object]这个无效字符串,服务器自然无法解析出有效数据。
你需要做两件事:
- 用
JSON.stringify()把对象转为JSON字符串 - 设置
Content-Type: application/json请求头,告知服务器请求体的格式
修改后的前端代码:
async function refetch(btn) { if (btn.innerHTML === 'Edit') { await fetch('http://localhost:3000/todo', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ edit: 'true' }) }) } }
2. 服务器未配置JSON解析中间件
Express框架默认不会自动解析JSON格式的请求体,必须手动添加express.json()中间件,才能让req.body获取到解析后的JSON数据。注意中间件要放在所有路由定义之前。
修改后的服务器代码:
// 新增JSON解析中间件 app.use(express.json()); app.put("/todo", (req, res) => { console.log(req.body); // 现在可以正常输出 { edit: 'true' } });
内容的提问来源于stack exchange,提问作者ether
相关产品推荐
相关产品推荐

