Manipulation of Middleware

Asked

Viewed 51 times

1

I’m trying to do the following manipulation on Expressjs.

I took an MEAN Stack project and the person I was developing came out and I’m just following through. But now I’ve come across the following situation::

When I make 2 requests on mongoDB to list client and list the separate regions it only executes either one or the other.

Follow the code below (the function verificaAutenticao would be the standard call req,res,next):

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

 app.route('clientes')
    .get(verificaAutenticacao, controller.listaClientes, 
       controller.listaRegionais);
}

1 answer

0

I’m gonna break your code into a few parts so you can understand what’s going on:

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

You create a route /clientes responding to a HTTP GET Request. This route, when triggered (for example, entering http://enderecodoservidor.com/clientes browser), will trigger all middleware within that function in order:

  1. verificaAutenticacao
  2. listaClientes
  3. 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();
}

The call of the method next, makes the objects req and res are 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 method next; signalling that the next function in the "current of middleware" (in that case, listaRegionais), should be called, with the same objects req and res.

The error is somewhere in that current/call chain.

If, for example, the first middleware do not verify the authentication as valid, it is perfectly plausible to create a code to return a sponse premature (a 400 error, for example). In this case, the rest of the middleware would not be taken into consideration.

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 the page that talks about middleware in the original documentation.

I believe it’s worth it to you to create a middleware for a deeper learning.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.