Middleware Manipulation

1

I'm trying to do the following handling in ExpressJS.

I picked up a MEAN Stack project and the person I was developing came out and I'm just continuing. But now I came across the following situation:

When I make 2 requests in mongoDB to list client and list the separate regions it just runs either one or the other.

Here is the code below (the function verificaAutenticao would be the default call req, res, next):

module.exports = function(app)
{
 var controller = app.controllers.maps.cliente;

 app.route('clientes')
    .get(verificaAutenticacao, controller.listaClientes, 
       controller.listaRegionais);
}
    
asked by anonymous 14.09.2017 / 19:19

1 answer

0

I'll break your code in some parts so you understand what's going on:

app.route('clientes').get()

You create a /clientes route that responds to a HTTP GET Request . This route, when triggered (for example, by going to link in your browser), will link all the middlewares within this function in order :

  • verificaAutenticacao
  • listaClientes
  • listaRegionais
  • The first middleware ( verificaAutenticacao ) is a function with the following signature:

    function(req, res, next){
    // ... executa código, podendo manipular os objetos req e res
    next();
    }
    

    Calling the next method causes the req and res objects to be passed to the next function with the same signature (middleware ) in the arguments. In this case, the function listaClientes .

    This function, in turn, is also a middleware , and at the end of it, if everything happens as expected, there should also be a call to the next method; signaling that the next function in the "middlewares stream" (in this case, listaRegionais ) should be called, with the same objects req and res .

    The error is at some point in this chain / call chain.

    If, for example, the first middleware does not verify authentication as valid, it is perfectly plausible to create a code to return a premature response example). In that case, the rest of the middlewares would not be taken into account .

    example:

    function verificaAutenticacao(req, res, next){
        if(req.auth.login === 'loginCorreto' && req.auth.password === 'senhaCorreta'){
            next(); // nesse caso, pode passar pro próximo middleware
        } else {
            res.sendStatus(400); // quebra a corrente, e acaba por aqui.
        }
    }
    

    For further questions, check out the middlewares page in the original documentation.

    I think it's worth you to create a middleware for deeper learning.

        
    10.09.2018 / 21:17