Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

109
Visualizações
usage of cors middleware vs custom middleware

Pardon me for this stupid question, but can someone explain me how the cors middleware work?

I accidentally called an auth middleware by adding brackets after it and it ran that middleware without even me requesting to that route.

I know that adding brackets after function invokes it but what is it with cors middleware that we add those brackets after it??

usage of cors middleware from docs:

app.get('/products/:id', cors(), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for a Single Route'})
})

using auth middleware with () gives error:

app.get('/products/:id', auth(), function (req, res, next) {
  res.json({msg: 'This is an authorized Route'})
})

usage of auth middleware without () works fine:

app.get('/products/:id', auth, function (req, res, next) {
  res.json({msg: 'This is an authorized Route'})
})
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Functions can return other functions, when you call the cors function using cors(), you get back a new function, that is used as the middleware function in app.get(). Your cors() example could be rewritten like so:

const corsMiddlewareFn = cors();
app.get('/products/:id', corsMiddlewareFn, function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for a Single Route'})
})

Above we store the function that calling cors() returns in a variable called corsMiddlewareFn, and then we use that as middleware as part of the call to app.get(). Having cors() return a function is useful as it allows us to pass options to the cors() function so that the middleware function it returns can use those options accordingly.

On the other hand, your auth function most likely doesn't return a function, so auth itself is the middleware function you want to use, and not its return value which you would get when calling auth().

about 4 years ago · Juan Pablo Isaza Relatório

0

The cors module returns a function that takes optional configuration and returns the middleware.

The auth is already the middleware, not a function, so no need to call it.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda