Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

166
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!