问题及现象
开发过程使用curl+PUT方式发送少量数据, 后端使用NodeJS+express框架+bodyParser,但测试发现无法获取到请求体内容,现象表现为req.body 为空对象 {}
代码如下:
const bodyParser = require('body-parser');
router.use('/api/1', bodyParser.raw({limit: '10mb', type: '*/*'})); //中间件处理
router.put('/api/1', (req,res,next)=>{console.log(req.body); //输出为{}res.send('OK');})
使用curl -T 1.log http://127.0.0.1:8080/api/1 测试
curl -T 1.log http://127.0.0.1:8080/api/1
手动接收并打印请求体, 是能正常得到的,
router.put('/api/2', (req,res,next)=>{console.log(req.headers); //输出请求头信息console.log(req.pipe(process.stdout)); //正常输出res.send('OK');})
问题原因
经定位发现, curl默认使用put上传文件时, 默认不发送Content-Type
, 而bodyParser判定type的依据是Content-Type
匹配, 故此种情况下实际上中间件并没有执行, req.body为空;
解决方法
方案1 curl发送时增加Content-Type
curl -T 1.log -H 'Content-Type:text/plain' http://127.0.0.1:8080/api/1
后端代码无需修改;
方案2 后端服务兼容这种不带Content-Type
的请求
router.use('/api/1', bodyParser.raw({limit: '10mb', type: ()=>true})); //中间件处理, 自定义type的判定函数,直接返回true