I always see bodyParser being used to give you access to the posted form stuff. By making it accessible in req.body
. But how would you access that data if you didn't want to use bodyParser
?
Related/similar question - how does bodyParser
provide you with the data in req.body
?
Edit: I'm asking about how this stuff works on a low level. This possible duplicate seems to be addressing it by recommending certain middleware and describing how to use them.
Top Alternatives to body-parser js. JavaScript library for DOM operations. React is a JavaScript library for building user interfaces. React package for working with the DOM.
Avoid bodyParser and explicitly use the middleware that you need. If you want to parse json in your endpoint, use express. json() middleware. If you want json and urlencoded endpoint, use [express.
To parse the POST request body in Node JS without using Express JS body-parser, We have to listen events, emitted by the request, ie. 'data' event and 'end' event. Above we are using Buffer. concat(), it is a method available in Node JS Buffer class, it join all the received chunks and returns a new Buffer.
Express body-parser is an npm module used to process data sent in an HTTP request body. It provides four express middleware for parsing JSON, Text, URL-encoded, and raw data sets over an HTTP request body.
bodyParser is a middleware that parses the stream of data to a json. I can't see a reason to not use bodyParser (if you don't want to handle multipart bodies), but you can parse the streaming by yourself if you want to. It will be something like the middleware below:
app.use(function( req, res, next ) {
var data = '';
req.on( 'data', function( chunk ) {
data += chunk;
});
req.on( 'end', function() {
req.rawBody = data;
console.log( 'on end: ', data )
if ( data && data.indexOf( '{' ) > -1 ) {
req.body = JSON.parse( data );
}
next();
});
});
If you want to parse multipart bodies you can use one of the following modules:
A cursory answer to this is to use https://github.com/stream-utils/raw-body to parse the request body and then run your JSON.parse on the result. This is how body-parser gets the request body from which it then parses json, urls, and raw text data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With