Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you access form data without using bodyParser?

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.

like image 519
Adam Zerner Avatar asked Jul 01 '15 17:07

Adam Zerner


People also ask

What is the alternative of bodyParser?

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.

What can I use instead of bodyParser JSON?

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.

How can I get data without body-parser?

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.

Why is bodyParser needed?

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.


2 Answers

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:

  • busboy
  • multiparty
  • formidable
  • multer
like image 63
gmartini20 Avatar answered Nov 14 '22 22:11

gmartini20


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.

like image 37
keepitreal Avatar answered Nov 14 '22 21:11

keepitreal