Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does `app.use(bodyParser.json())` do?

For:

bodyParser.urlencoded({extended: ...})

my research shows me that if extended: true, then you can parse nested objects, or generally any type. However, if you set extended: false, then you can only parse strings or arrays. But what does ...

app.use(bodyParser.json())

mean exactly? I mean, yes... I know the docs mention that it parses json. But I am still confused. I have noticed applications that set extended: true do NOT use bodyParser.json() at all. But applications that extended: false tend to use bodyParser.json(). Why is this? At the end of the day, both applications are able to parse json.

Secondly, which is the recommended approach?

like image 673
Grateful Avatar asked Oct 05 '16 09:10

Grateful


People also ask

Why do we use bodyParser?

In order to get access to the post data we have to use body-parser . Basically what the body-parser is which allows express to read the body and then parse that into a Json object that we can understand.

Is bodyParser needed?

Conclusion. You might not need to install the additional body-parser package to your application if you are using Express 4.16+. There are many tutorials that include the installation of body-parser because they are dated prior to the release of Express 4.16.

What does bodyParser do in Nodejs?

Body-parser is the Node. js body parsing middleware. It is responsible for parsing the incoming request bodies in a middleware before you handle it.

What is app use express JSON ())?

a. express. json() is a method inbuilt in express to recognize the incoming Request Object as a JSON Object. This method is called as a middleware in your application using the code: app. use(express.


Video Answer


2 Answers

Okay, contrary to what I previously thought, further research shows that extended: true and app.use(bodyParser.json()) can be used together. So it is not only extended: false that uses it. The statement app.use(bodyParser.json()) is to be used independently, whether you set extended as true or false.

  • app.use(bodyParser.json()) basically tells the system that you want json to be used.

  • bodyParser.urlencoded({extended: ...}) basically tells the system whether you want to use a simple algorithm for shallow parsing (i.e. false) or complex algorithm for deep parsing that can deal with nested objects (i.e. true).

Have a look at the docs (i.e. https://expressjs.com/en/guide/migrating-4.html) for the example.

like image 86
Grateful Avatar answered Oct 19 '22 22:10

Grateful


URL encoding and JSON encoding both allow to convert a (nested) object to string, but the format is different. An URL encoded string is in general not a valid JSON string.

One application may use one encoding method, and another the other. As long as they don't mix the two, it will work.

like image 8
trincot Avatar answered Oct 20 '22 00:10

trincot