app.use(bodyParser.json());
客戶端請求接口時如果指名請求頭類型 為Content-Type=application/json
bodyParser 會自動將 body 里的 json 格式數據正確解析,
// bodyParser 依賴 raw-body 庫,raw-body庫里面有這樣一段代碼
function cleanup() { received = buffer = null stream.removeListener('data', onData) stream.removeListener('end', onEnd) stream.removeListener('error', onEnd) stream.removeListener('close', cleanup) }
這樣導致在express里面req監聽on, end事件是不會執行的.要想在express里面拿到request的原始數據
可以再注冊bodyPaser之前先把原始數據保存起來.代碼如下:
app.use(function(req, res, next){ var reqData = []; var size = 0; req.on('data', function (data) { console.log('>>>req on'); reqData.push(data); size += data.length; }); req.on('end', function () { req.reqData = Buffer.concat(reqData, size); }); next(); }); app.use(bodyParser.json()); app.use(bodyParser.urlencoded());