Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

publicShare is looks like

var publicShare = function(req, res, next) {
    if (condition1) {
        if (condition2) {
            res.status(400).send({success:false});
        } else {
            next();       
        }
    } else {
        if (condition3) {
            res.status(401).send({success:false});
        } else
            next();
    }
};

Please help me to understand.

like image 487
GRESPL Nagpur Avatar asked Jan 01 '23 07:01

GRESPL Nagpur


1 Answers

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!

like image 191
Bhojendra Rauniyar Avatar answered Jan 05 '23 01:01

Bhojendra Rauniyar