I have a confusion while using the bodyparser.Why do we actually need bodyparser when we have json.stringify(to convert object to string) and json.parse(to convert JSON to object)
is it because using it in our app.use() automatically applies the middleware during the interchange of data between client and the server? and we don’t need to specify each time when the sending the data from client to server and vice versa?
and if it is so what is the difference between urlencoded and json in bodyparser?
2
Answers
Yes, you are correct.
Body-parser
is a middleware that automatically parses incoming request bodies and makes the data available inreq.body
property. It eliminates the need to manually parse the request body each time a request is made, saving time and reducing the risk of bugs.The difference between
urlencoded
andjson
in body-parser is the format of the incoming request body.urlencoded
is used when the request body is encoded as URL-encoded strings (i.e. x-www-form-urlencoded) while JSON is used when the request body is in JSON format. By using both, you can handle different types of request bodies.The body parser is also responsible for reading the data from the network stream of the HTTP request in the first place. You can’t parse data until you have it.
They parse bodies written in different data formats. The urlencoded format is the default encoding format for a
<form>
.