Search code examples
javascriptnode.jsexpressparameter-passingrequire

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 ).


Solution

  • 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);