問題及現象
開發過程使用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