Skip to content Skip to sidebar Skip to footer

What Is Second Parameter In Nodejs Post Method

In my code I have code written like this router.post('/', publicShare, function(req, res, next) { I check in documents but not found why second param publicShare is here? publicS

Solution 1:

You can check route handlers which accepts array of callbacks which just behaves like a middleware. Example from the docs:

app.get('/example/d', [cb0, cb1], function (req, res, next) {

So, in your case publicShare can be array of callbacks or just a callback which signature is just a callback accepting req, res, and next as parameter. So, you can also use like:

app.get('/', function(req, res, next){}, function(req, res, next){}, ...

And for easier, you would use an array of callbacks:

app.get('/',[cb1, cb2, cb3])

Where cb1, cb2, and cb3 are the callbacks with request, response and next parameters. It allows you to run one by one. cb1 -> do log 1, then cb2 -> do log 2, cb3 -> do log 3 and so on.

I would simplify this with an example:

You would request for water.

1) cb1: Purchase a jar of water.

2) cb2: Add few water drops in the bucket or jar.

3) cb3: Boil it.

Then, it's your turn. Drink!


Solution 2:

publicShare method in your route is a express middleware function .According to the docs

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle

A middleware checks for certain condition or criteria to be applied on your request and response object ,if the criteria fulfills then the next operation is done ,which is either

1-End the request response cycle

2-Call the next middleware function in the stack.

You can refer the docs for more information -https://expressjs.com/en/guide/using-middleware.html


Solution 3:

According to the documentation, you can add multiple middleware functions separated by commas. The 'publicShare' variable must be a middleware function.


Post a Comment for "What Is Second Parameter In Nodejs Post Method"