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

167
Visualizações
Parameter express can't be passed with require

app.js

const express = require("express");
const app = express();

app.use("/", require("./routers.js")(app));

app.listen(3000);

router.js

module.exports = function (app) {
  console.log(app);
  app.get("/", (req, res) => {
    res.json(5);
  });
};

The error given by the Console is: " TypeError: Router.use() requires a middleware function but got an undefined "

I don't understand why I can't pass the express app(app.js) through routers( in this way I don't redeclare the express and app variable in router.js ).

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

0

Don't pass app to routes better to create a new router and pass to the app.

router.js

const express = require("express");
const router = express.Router();
router.get("/", (req, res) => {
  res.json(5);
});
module.exports = router;

app.js

app.use("/", require("./routers.js"));

As you mention in the comment, you don't have to add an inside app.use

module.exports = function (app) {
  app.get("/", (req, res) => {
    res.json(5);
  });
};

// app.js
require("./routers.js")(app);
about 4 years ago · Juan Pablo Isaza Relatório

0

The use method of Express needs a callback of three parameters, not the app itself, so you need something like this:

In routes.js

exports.doSomeThing = function(req, res, next){
    console.log("Called endpoint");
    res.send("Called endpoint");
}

In your index.js

const Express = require("express");
const app = Express();
const routes = require("./routes");

app.use("/", routes.doSomeThing);

app.listen(3030, () => {
    console.log("Listening on port 3030");
});

This approach doesn't need to include the express router but this may not be adecuate for big scale projects I recommend you to read express router documentation:

https://expressjs.com/es/guide/routing.html#express-router

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