user1460015
user1460015

Reputation: 2003

Application works with app.all but not with app.use... not sure why

I'm having some problems trying to implement some middleware in my app.
Specicially, the app.use() does not seem to catch and I don't understand why.
Below is roughly what I have.

routes/index.js

var Sessions = require('../events');  

module.exports = exports = function(app) {

  app.use(Sessions.isLoggedIn);

  //app.use() does not catch but this does
  //app.all('*', Sessions.isLoggedIn); 

  // Home Page
  app.get('/', displayHome);
  app.get('/:library/:books', displayLibrary);

}

events.js

module.exports = exports = {

  isLoggedIn: function(req, res, next) {
      console.log('isLoggedIn');
      return next();
}

Any suggestions as to why app.use() is not catching?

UPDATE:
Here is the configuration in ape.js

app.configure(function() {
  app.set('port', process.env.VCAP_APP_PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.logger('dev'));
  app.use(express.compress()); // compress responses
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(expressValidator);
  app.use(express.cookieParser('locket'));
  app.use(express.cookieSession({
    key: 'locket',
    secret: 'mySecret',
    cookie: {httpOnly: true, expires: 0, path: '/'}
  }));

  // cache every file going out
  app.use(function(req, res, next) {
    if (!res.getHeader('Cache-Control')) {
      res.setHeader('Cache-Control', 'public, max-age=' + (86400 / 1000));
    }
    next();
  });

  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler({showStack: true, dumpExceptions: true}));
});

routes(app);

Upvotes: 0

Views: 235

Answers (1)

josh3736
josh3736

Reputation: 145162

The router is responding to the request before your middleware function has a chance to run.

app.js sets up several other middleware functions, then uses app.router. You then call your routes/index.js file, which uses a new middleware function which gets added after app.router.

use your isLoggedIn function before the router, or use it specifically with the routes that need to check login state:

app.get('/', Sessions.isLoggedIn, function(req, res) { ... });

Upvotes: 1

Related Questions