66

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?

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Grateful
  • 9,685
  • 10
  • 45
  • 77

3 Answers3

102

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.

Grateful
  • 9,685
  • 10
  • 45
  • 77
9

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.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • 1
    Can one application set extended as true and yet still have `app.use(bodyParse.json())`? Or does the latter always go with extended being false? But interestingly, both seem to work for json parsing. – Grateful Oct 05 '16 at 10:05
7

bodyParser.json returns middleware that only parses JSON. This parser accepts any Unicode 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).

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Malatesh Patil
  • 4,505
  • 1
  • 14
  • 14