使用curl/hurl发送请求时req.body返回空对象的技术求助
问题排查:Express中req.body为空对象但请求头正常的问题
使用curl或Hurl发送POST请求时,Express路由内req.headers['content-length']能返回正确长度、req.headers['content-type']符合预期,但req.body始终是空对象{}。
相关代码与请求示例
Hurl测试脚本
POST http://localhost:8080/v1/fragments Content-Type: text/plain [BasicAuth] user1@email.com:password1 `This is a fragment!`
等效curl命令
curl -i \ -X POST \ -u user1@email.com:password1 \ -H "Content-Type: text/plain" \ -d "This is a fragment" \ https://localhost:8080/v1/fragments
Express路由代码
router.post('/fragments', (req, res) => { let newuuid = uuidv4(); res.location(`http://localhost:8080${req.originalUrl}/${newuuid}`) .status(201) .json( createSuccessResponse({ fragment: { id: newuuid, ownerId: '11d4c22e42c8f61feaba154683dea407b101cfd90987dda9e342843263ca420a', created: '2021-11-02T15:09:50.403Z', updated: '2021-11-02T15:09:50.403Z', type: req.headers['content-type'], size: Number(req.headers['content-length']), }, }) ); });
问题原因与解决方法
核心原因
Express 默认不会自动解析请求体,必须手动添加对应类型的解析中间件,否则即使请求头信息正常,req.body也会是空对象。
解决步骤
在你的Express应用中,确保在路由注册之前添加请求体解析中间件:
- 如果仅处理
text/plain类型请求:const express = require('express'); const app = express(); // 添加text/plain解析中间件 app.use(express.text()); // 之后再注册你的路由 app.use('/v1', router); - 如果需要支持多种文本/二进制类型(如
text/plain、application/octet-stream等):app.use(express.raw({ type: '*/*' }));
添加后,req.body会被正确解析为对应格式的内容(express.text()会解析为字符串,express.raw()会解析为Buffer)。
内容的提问来源于stack exchange,提问作者alicode1111
相关产品推荐
相关产品推荐

