Express后端POST请求req.body显示undefined的问题求助
解决Express后端req.body为undefined的问题
你的问题核心原因是Express默认不会自动解析JSON格式的请求体,所以才会打印出Request body: undefined,解决方法如下:
- 确保项目已安装express(未安装的话执行命令:
npm install express) - 在Express入口文件(如app.js、server.js)中,所有路由注册之前添加JSON解析中间件:
app.use(express.json());
完整的后端示例代码:
const express = require('express'); const app = express(); // 必须先添加解析中间件,再注册路由 app.use(express.json()); app.post('/createUser', async (req, res) => { try { console.log('Request body:', req.body); // 务必给前端返回响应,避免请求挂起超时 res.status(200).json({ message: '请求已处理' }); } catch (error) { console.error('Error creating user:', error); res.status(500).json({ error: '服务器内部错误' }); } }); app.listen(5000, () => { console.log('服务器运行在 http://localhost:5000'); });
额外提醒:你的原后端代码没有返回响应,前端fetch请求会一直处于pending状态最终超时,记得加上响应返回逻辑。
内容的提问来源于stack exchange,提问作者simey
相关产品推荐
相关产品推荐

