Vlad Vinnikov Vlad Vinnikov - 1 year ago 109
Node.js Question

How to pass variable from app.js to routes/index.js?

I'm using shrinkroute https://npmjs.org/package/shrinkroute to make links in nodejs. I get error 500 ReferenceError: shrinkr is not defined

How to pass shrinkroute to routes/index.js? Is there a better way to create url by passing query string args?

var app = express();

var shrinkr = shrinkroute( app, {
"user": {
path: "/user/:id?",
get: routes.showOrListUsers
//url method works in app.js
var url = shrinkr.url( "user", { id: 5, page:40, type:'a' } );

app.use( shrinkr.middleware );

exports.showOrListUsers = function(req, res, next) {
//shrinkr errors out in index.js
var url2 = shrinkr.url( "users", {name: "foo"});

Answer Source

One solution would be to store shrinkr in your app object using app.set:

// app.js
app.set('shrinkr', shrinkr);

In routes/index.js, you can access it through the req.app or res.app objects:

exports.showOrListUsers = function(req, res, next) {
  var shrinkr = req.app.get('shrinkr');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download