Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express: accessing app.set() settings in routes

In Express, I'm led to believe that global app settings can be created by doing something similar to the following in my main app.js file:

var express = require('express'),
    ...
    login = require('./routes/login');

var app = express();

app.configure(function(){
  ...
  app.set('ssoHostname', 'login.hostname.com');
  ...
});
...
app.get('/login', login.login);
...

now in ./routes/login.js, I'd like to access app.settings.ssoHostname, but if I attempt to run anything similar to (as per: How to access variables set using app.set() in express js):

...
exports.login = function(req, res) {
  var currentURL = 'http://' + req.header('host') + req.url;
  if (!req.cookies.authCookie || !User.isValidKey(req.cookies.authCookie)) {
    res.redirect(app.settings.ssoHostname + '/Login?returnURL=' + encodeURIComponent(currentURL));
  }
};
...

it does not recognize app:

ReferenceError: app is not defined

My questions are:

  1. Is the approach I took of using app.set() for global settings that will be re-used often the "proper" way to do it and if so...
  2. How do I access these settings in routes?
  3. If not using app.set() for global settings to be used often, how would I set and get custom settings in routes?
like image 410
Scott Avatar asked Feb 11 '13 23:02

Scott


People also ask

What does Express router () do?

The express. Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests.

How can we create Chainable route handlers for a route path in Expressjs app?

Answer: A is the correct option. By using app. route() method, we can create chainable route handlers for a route path in Express.

What are route parameters in Express?

Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the req. params object, with the name of the route parameter specified in the path as their respective keys.

What function arguments are available to express JS route handlers?

The arguments available to an Express. js route handler function are: req - the request object. res - the response object.


2 Answers

Use req.app.get('ssoHostname')

like image 132
Darius Kucinskas Avatar answered Oct 12 '22 04:10

Darius Kucinskas


At the end of your app.js file:

module.exports = app;

And then in routes/login.js:

var app = require('../app');

Now you have access to the actual app object and won't get a ReferenceError.

like image 21
pifantastic Avatar answered Oct 12 '22 05:10

pifantastic