how to share variables between routes node
var router = require("express").Router() var varSetMiddleware = function(res,req,next){ router.variable = 100 // set the variable inside the router object // now you can access it anywhere in this specific router next() } router.get("/first_view", function (req, res) { // something console.log(router.variable) //100 res.send("something") }) router.get('/second_view', function (req, res) { // something console.log(router.variable) //100 res.send("something") module.exports = router
Here is what the above code is Doing:
1. We are creating a variable called varSetMiddleware.
2. We are setting a variable called variable inside the router object.
3. We are using the variable inside the router object in the first_view and second_view routes.