Home > Blockchain >  Parameter express can't be passed with require
Parameter express can't be passed with require

Time:01-05

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

CodePudding user response:

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

CodePudding user response:

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

  •  Tags:  
  • Related