What is the mean of "bodyParser.urlencoded({ extended: true }))" and "bodyParser.json()" in NodeJS?

body-parser is an NPM package that parses incoming request bodies in a middleware before your handlers, available under the req.body property.

app.use(bp.json()) looks at requests where the Content-Type: application/json header is present and transforms the text-based JSON input into JS-accessible variables under req.body. app.use(bp.urlencoded({extended: true}) does the same for URL-encoded requests. the extended: true precises that the req.body object will contain values of any type instead of just strings.


Full documentation of body-parser library can be found here.

bp.json() - middleware for parsing json objects - options can be found here. Source code can be found here.

Returns middleware that only parses JSON and only looks at requests where the Content-Type header matches the type option. This parser accepts any Unicode encoding of the body and supports automatic inflation of gzip and deflate encodings.

bp.urlencoded({ extended: true }) - middleware for parsing bodies from URL. Options can be found here. Source code can be found here.

Returns middleware that only parses {urlencoded} bodies and only looks at requests where the Content-Type header matches the type option. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings.

A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body). This object will contain key-value pairs, where the value can be a string or array (when extended is false), or any type (when extended is true).


It helps you to create object from the form input

  <input type="text" class="form-control" placeholder='Text' name="comment[text]" value="<%=comment.text%>">

those two line will help you produce a object directly without the hassle to set variables and create your own object.if you set extended property to false it will not produce the object and will return undefined.try it for yourself you will know

Tags:

Node.Js