0

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

When I do this only 1 controller is called what is wrong?

lapinkoira
  • 8,320
  • 9
  • 51
  • 94

2 Answers2

0

if what you're talking about is nodejs express and you're trying to add multiple middlewares to a route you should use the following syntax:

app.get('/example/b', function (req, res, next) {
  console.log('the response will be sent by the next function ...')
  next()
}, function (req, res) {
  res.send('Hello from B!')
})
Santiago Benitez
  • 364
  • 2
  • 12
  • I tried to do this, but when I did I took an error: UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent. – Bruno Oliveira Sep 13 '17 at 14:57
  • controller.listaClientes = function(req, res, next) { var filtro = {}; Cliente.find(filtro) .exec() .then( function(listagem) { res.json(listagem); }, function(erro) { console.log(erro); res.status(500).json(erro); } ); next() }; – Bruno Oliveira Sep 13 '17 at 14:58
  • so first instead of having a second callback for then just do .catch at the end: .then(function(){...}).catch(function(){..}) and second you can only do res.json only once. If you do that the res will be marked as finalised and you won't be able to set the headers again. I don't know why you're having so many middlewares but make sure you're finishing the response only once. You can find more information here https://stackoverflow.com/questions/7042340/error-cant-set-headers-after-they-are-sent-to-the-client – Santiago Benitez Sep 13 '17 at 16:04
  • let me know if this helped, but if you do the example i showed you and also resolve the response once (at the end) and the other middlewares you just do some processing or whatever you want to do and then you call next() it should work. – Santiago Benitez Sep 13 '17 at 16:46
0

I resolved the problem...

I'm new in Express, Angular and mongo so after looking and search some logic i found the answer.

When I make a route.get and pass middleware I need create a new path, which refers about that function middleware.