Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

171
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda