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

142
Visualizações
Calling a function inside route handler vs using a middleware

I am trying to understand if there is any difference. I'll try to explain it with an example from express docs: https://expressjs.com/en/guide/using-middleware.html

function logOriginalUrl (req, res, next) {
  console.log('Request URL:', req.originalUrl)
  next()
}

function logMethod (req, res, next) {
  console.log('Request Type:', req.method)
  next()
}

const logStuff = [logOriginalUrl, logMethod]
app.get('/user/:id', logStuff, (req, res, next) => {
  res.send('User Info')
})

logOriginalUrl and logMethod are middlewares in this example. What would happen if I write it like:

function logOriginalUrl() {
  console.log('Request URL:', req.originalUrl);
}

function logMethod() {
  console.log('Request Type:', req.method);
}

app.get('/user/:id', (req, res, next) => {
  logOriginalUrl();
  logMethod();
  res.send('User Info')
})

Is there any difference between these two? This is a very simple example but it can be applied for any other example where you have to manipulate req or do anything else.

What is the difference between a middleware and calling + awaiting a function inside route handler?

Theoretically, anything I can do as middleware, I feel like I can achieve exact same thing by awaiting same function in route handler function. So, what do I miss?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your second code will throw an error because req is undefined in the scope of logOriginalUrl and logMethod.

But if you would pass this data correctly, there would be absolutely no difference. Middlewares are for convenience.

They are used to handle common scenarios betweem routes and make the code more readable.

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