Express parse content in body or query params

Problem

I have an endpoint that accepts json either in the URL or the message body (POST of course)

app.post('/book/addBooks', function (req, res) {
...

I know that the new book JSON coming from the server is going to either be a query param

<server>/book/addBooks?books=[{...},{...}]

or from the body

<server>/book/addBooks

body:

books=[{...},{...}]

Basically I am checking for both:

req.body.books

or

req.query.books

And picking the first one that has content. Is there a better way to get at the 'books' in express?

Side note: before you trash the fact that you can pass in url or body I am writing a service that mimics another API, since the other API allows this junk I have to as well.

Problem courtesy of: lostintranslation

Solution

From express docs

req.param(name)

Return the value of param name when present.

// ?name=tobi req.param('name') // => "tobi"

// POST name=tobi req.param('name') // => "tobi"

// /user/tobi for /user/:name req.param('name') // => "tobi"

Here is the lookup order:

Lookup is performed in the following order:

req.params
req.body
req.query
Solution courtesy of: lostintranslation

Discussion

case use req.params : when is a rest value example

/users/:id  

req.body : when send data for method post req.query : when send data for method get example

 /users?thisIsaVar=thisIsaValue 

ok, expressjs the post method is body

Discussion courtesy of: user3758205

This recipe can be found in it's original form on Stack Over Flow.