skip to Main Content

I am writing an express app with multiple routes. Each route will have it’s own file for modularity and all route files will be in a routes folder.

I have a value that is reused across all the routes. How do I share it from my app.js file to a route.js file.

Example

//app.js file

const express = require("express");

const app = express();

const port = 3000;

const url = "https://example.com/v1"; // how do I pass this value to the test route below?

const test = require("./routes/test")

app.use(express.json());



app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});
// routes/test.js

const express = require("express");
const router = express.Router();


//middleware for requests
router.use((req, res, next) => {
  console.log("Time:", Date.now());
  next();
});


router.post("/", (req, res) => {
 console.log(url)
});

2

Answers


  1. You can make the routes as function and pass params like

    your main file

    const v1Routes = require('./routes/v1/');
    
    app.use('/', middleware(), v1Routes({ userid : 123 }));

    you route file

    const routes = require('express').Router({ mergeParams: true })
    
    module.exports = (params) => {
        routes.use('/user', require('./user')(params));
        return routes;
    }

    your controller file

    module.exports = (params) => {
        return (req, res, next) => {
    
            console.log(params.userid)
            res.status(200).json({ message: 'All good' });
    
        }
    }
    Login or Signup to reply.
  2. app.js I am missing app.use("/test", test) and you can change const test = require("./routes/test") to const test = require("./routes/test")(url):

    const express = require("express");
    const app = express();
    
    const port = 3000;
    const url = "https://example.com/v1";
    
    //const test = require("./routes/test")
    const test = require("./routes/test")(url);
    
    app.use(express.json());
    app.use("/test", test);
    
    app.listen(port, () => {
      console.log(`Example app listening on port ${port}`);
    });
    

    routes/test.js: I am missing a module.exports

    const express = require("express");
    const router = express.Router();
    
    module.exports = (url) => {
      router.post("/", (req, res) => {
        res.json({ url: url });
      });
      
      return router;
    };
    

    request: test it with

    curl --location --request POST 'http://localhost:3000/test'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search