rob_hicks
rob_hicks

Reputation: 1744

Passing a value to a Node js module for Express routes

I want to pass the environment for Express to a routing module for Express. I want to key off of whether Express is running in development or production mode. To do so, I'm guessing I need to pass app.settings.env somehow to a routing module.

My routing module exports a function for each route. So:

app.get('/search', web.search);

Based upon a previous stackoverflow post, i have tried this:

var web = require('./web')({'mode': app.settings.env});

But node throws an type error (object is not a function).

I'm new to Node and Express. Can I pass a value to an express route and if so, how?

Upvotes: 5

Views: 3039

Answers (1)

Vadim Baryshev
Vadim Baryshev

Reputation: 26219

If you web.js looks like this:

module.exports.search = function(req, res, next) {
    // ...
};

module.exports.somethingOther  = function(req, res, next) {
    // ...
};

then by calling

var web = require('./web')({'mode': app.settings.env});

you try to use object (module.exports) as function. Type error here.

You need to convert module.exports to function to pass parameters to it. Like this:

module.exports = function (env) {
    return {
        // env available here
        search: function(req, res, next) {
            // ...
        },

        somethingOther: function(req, res, next) {
            // ...
        };
    };
};

Upvotes: 8

Related Questions