Created
March 13, 2018 22:32
-
-
Save max8hine/f6475a1b75a85b119feffc26a4e6040e to your computer and use it in GitHub Desktop.
[Express.js] Get raw Data from req.on when you use body-parser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
`app.use(bodyParser.json())` | |
`Content-Type=application/json` | |
BodyParser will parses json data correctly | |
And cleanup() from raw-body, a dependency of body-parser will clean-up the raw data | |
*/ | |
function cleanup() { | |
received = bufer = null | |
stream.removeListener('data', onData) | |
stream.removeListener('end', onEnd) | |
stream.removeListener('error', onEnd) | |
stream.removeListener('close', cleanup) | |
} | |
/* | |
It will lead to `on` and `end` event won't be executed | |
So, if want to get raw-data from request, you need to do | |
*/ | |
app.use(function(req, res, next){ | |
const reqData = [] | |
const size = 0 | |
req.on('data', data => { | |
reqData.push(data) | |
size += data.length | |
}) | |
req.on('end', () => { | |
req.reqData = Buffer.concat(reqData, size) | |
}) | |
next() | |
}) | |
app.use(bodyParser.json()) | |
app.use(bodyParser.urlencoded()) | |
// https://www.cnblogs.com/hubcarl/p/4066183.html |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment