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
You can make the routes as function and pass params like
your main file
you route file
your controller file
app.js I am missing
app.use("/test", test)
and you can changeconst test = require("./routes/test")
toconst test = require("./routes/test")(url)
:routes/test.js: I am missing a
module.exports
request: test it with