TheDeadMays
TheDeadMays

Reputation: 81

How to pass a variable through routes in Express

app.js

var express = require('express');
var app = express();

var testVar = "Hello World";

var index = require('./routes/index');

app.use('/', index);

index.js

var express = require('express');
var router = express.Router();

router.get('/', function(req, res) {
   console.log(testVar);
});

module.exports(router);

How to pass the variable "testVar" in ./routes/index.js? Someone has an idea? Thanks in advance!

Upvotes: 2

Views: 154

Answers (4)

Anand S
Anand S

Reputation: 1138

I don't know your purpose for doing this. But this is how you can send data to ./routes/index.js without middleware and also get the router.

index.js

var express = require('express');
var router = express.Router();
var testVar = null;

router.get('/', function(req, res) {
   console.log(testVar);
});

module.exports = function(testData){
    testVar = testData;
    return router;
}

app.js

var testVar = "Hello World";
var index = require('./routes/index')(testVar);

Upvotes: 0

thexpertdev
thexpertdev

Reputation: 122

You can pass a variable like below


   app.get('/user/:testVar', function (req,res,next) {
    });

Then retrieve the parameter with

req.params.testVar

Upvotes: 0

michelem
michelem

Reputation: 14590

You can do this in app.js:

app.use(function (req, res, next) {
    req.testVar = testVar;
    next();
});

Then in index.js just get the req variable you set before:

router.get('/', function(req, res) {
   console.log(req.testVar);
});

Upvotes: 1

NeedCoffee
NeedCoffee

Reputation: 70

You can do that in a middleware like this:

var express = require('express');
var app = express();

var testVar = "Hello World";

var myMiddleWare = function (req, res, next) {
    req.testVar = testVar;

    next();
}

var index = require('./routes/index');

app.use('/', myMiddleWare, index);

The middleware is called for every request to the index.

The only difference to a normal route-function is the third parameter "next", which might be called to go to the next step (the index), or not called (in case an error happend or something else)

You can read more about middlewares here: http://expressjs.com/en/guide/using-middleware.html

Upvotes: 1

Related Questions