Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding custom properties to Express app and req. What's the best way?

Am I shooting myself in the foot:

I want to make config, core, and mean available on the app and req objects in my Express app.

I'm using properties not in the 4.x API. Anything I should know?

Is there a problem with just adding them as properties?

// express.js
module.exports = function(db, config, meanModules) {

  var app = express();

  // ... 

  // Get mean-core
  var core = require('meanjs-core')(db, config);

  // Attach config, core, and modules to app    <==== POSSIBLE FOOT SHOOTING
  app.config = config;
  app.core = core;
  app.mean = meanModules;

  // Middleware to adjust req
  app.use(function(req, res, next) {
    // Add config, core, and modules to all requests  <==== POSSIBLE FOOT SHOOTING
    req.config = config;
    req.core = core;
    req.mean = meanModules;
    next();
  });

  // ...
}
like image 976
Michael Cole Avatar asked May 17 '14 22:05

Michael Cole


People also ask

Which property of the request object in Express framework helps to retrieve the query parameters?

The req. query property is an object containing the property for each query string parameter in the route.

Which method will you use in your Express application to get JSON data from the client side?

The req. body object allows you to access data in a string or JSON object from the client side. You generally use the req. body object to receive data through POST and PUT requests in the Express server.

What is req and res in Express?

The req object represents the HTTP request and has properties for the request query string, parameters, body, and HTTP headers. The res object represents the HTTP response that an Express app sends when it gets an HTTP request. In our case, we are sending a text Hello World whenever a request is made to the route / .

What is the difference between app use and app get in Express js?

app. get is called when the HTTP method is set to GET , whereas app. use is called regardless of the HTTP method, and therefore defines a layer which is on top of all the other RESTful types which the express packages gives you access to.


1 Answers

I would recommend attaching a single property to app that's probably never going to conflict, and accessing everything from there, like app.myLibrary.

app.myLibrary = {config: config, core: core, mean: meanModules};

And access app.myLibrary from within routes/middleware:

req.app.myLibrary

Unless something dynamic is happening in the middleware that varies per request, it's likely better to just access it with req.app.myLibrary.

like image 185
furydevoid Avatar answered Sep 26 '22 01:09

furydevoid