Skip to content

Instantly share code, notes, and snippets.

@max8hine
Created March 13, 2018 22:32
Show Gist options
  • Save max8hine/f6475a1b75a85b119feffc26a4e6040e to your computer and use it in GitHub Desktop.
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
/*
`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