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:
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();
}
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.