2

I came across lots of blogs and article they have suggested to use body-parser to parse request body data . Is there any way to parse-data or get body data from body without using any middle-ware?

Sachin G.
  • 155
  • 9
  • Yes. You can add events on your req object to listen to `data` and parse it on `end`. I used to do it but it is so much more work to do. That's why body-parser comes in handy – lumio Jul 24 '17 at 16:43
  • 2
    Possible duplicate of [What does body-parser do with express in nodejs?](https://stackoverflow.com/questions/38306569/what-does-body-parser-do-with-express-in-nodejs) – Andrew Li Jul 24 '17 at 16:44
  • @AndrewLi Disagree. They knows what it does in this case, but want to know if you have to use or if there is an alternative way to do it. The question you linked wanted to know what `body-parser` was. – Adam LeBlanc Jul 24 '17 at 16:46

2 Answers2

2

By default, express just gives you the raw HTTP request body in the req argument as a IncomingMessage which is basically a Readable stream. When you, e.g., make a form POST request, the form might be encoded in various ways if made by a web browser or it might be JSON or some arbitrary format. The body-parser module knows how to read the HTTP request body and understands a particular list of various common encodings.

Express is mostly just a very simple framework for hooking middleware together and declaring routing for your application. By doing very little and doing very well at it, it is unopinionated and usable by more people. For example, if you wanted to send your own format in an HTTP request, you might need to write your own code instead of using body-parser. Some HTTP server frameworks have a baked-in equivalent. In such frameworks, it might be hard/confusing to extend the body parsing functionality or even impossible. The Express project suggests body-parser, but if there’s a different module which parses the body in a way you like better, you can always use that instead.

binki
  • 7,754
  • 5
  • 64
  • 110
0

The express middleware is an unopinionated web framework, so if you want to parse results as JSON/form/multipart you need to tell the express how you need to parse the body.

Here comes the body-parser, you should use it as it is your requirement to parse the body as JSON or anything else, till then your request body will always be a stream.

Rohit Gupta
  • 2,571
  • 3
  • 16
  • 25