Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access "app" variable inside of ExpressJS/ConnectJS middleware?

This may not me be the right approach, but I want to conditionally add an object/parameter to the app variable inside of an expressJS/connectjS middleware call.

Since this function is a callback, what's the standard/best way to access app from inside a middleware call?

  //app.js   var myMiddleware = require('./lib/mymiddleware.js');   ...   app.configure( function(){     app.use( myMiddleware.func() );     ...   }    if( 'object' !== typeof app.myObject ){     cry( 'about it' );   }      //mymiddleware.js   module.exports.func = function( ){     return function( req, res, next ){        //append app object        //app.myObject = {}        next();     }   }; 

Note, this is not something for locals or settings to later be rendered, but something that will be used in routes and sockets later down the execution chain.

like image 480
qodeninja Avatar asked Sep 18 '13 18:09

qodeninja


People also ask

How do you store local variables that can be access within the application in ExpressJS?

5) What is the way to store local variables that can be accessed within the application? Answer: C is the correct option. We can store local variables that can be accessed within the application by using app. locals.

What does middleware in Express access?

Middleware literally means anything you put in the middle of one layer of the software and another. Express middleware are functions that execute during the lifecycle of a request to the Express server. Each middleware has access to the HTTP request and response for each route (or path) it's attached to.

What objects does middleware have access to through its parameters?

Middleware functions are functions that have access to the request object ( req ), the response object ( res ), and the next function in the application's request-response cycle.

How do I create a global variable in Express?

To make a global variable, just declare it without the var keyword. (Generally speaking this isn't best practice, but in some cases it can be useful - just be careful as it will make the variable available everywhere.) //we can now access 'app' without redeclaring it or passing it in... /* * GET home page. */ app.


2 Answers

Request objects have an app field. Simply use req.app to access the app variable.

like image 74
Nitzan Shaked Avatar answered Oct 14 '22 03:10

Nitzan Shaked


Generally I do the following.

var myMiddleware = require('./lib/mymiddleware.js')(app); ... app.configure( function(){   app.use( myMiddleware );   ... } 

And the middleware would look like this...

module.exports = function(app) {   app.doStuff.blah()    return function(req, res, next) {     // actual middleware   } } 
like image 25
Morgan ARR Allen Avatar answered Oct 14 '22 03:10

Morgan ARR Allen