1

First i want to say that i am a beginner when it comes to programming regardless of the language, and secondly, i am trying all the javascript + node.js and all their frameworks/modules since bearly a week.

So far i was able to find and fix all my problems with the help of StackOverflow but this time, i am stuck and really can't figure out why ; may be some noob reason or something deeper.

I am trying to make some basic feature for a website, right now i am working on a simple authentication code, so i wanted to save some client datas into session variables ; i have seen some example where you would first check if the session variables were defined and if not, doing so.

Here the example code:

.use(function(req, res, next){
  if (typeof(req.session.todolist) == 'undefined') {
    req.session.todolist = [];
  }
  next();
})

Which i wanted to change to:

.use(function(req, res, next) {
  if (typeof(req.session.auth) == 'undefined') 
    req.session.auth = false;
  next();
})

But nothing really, the variable stays undefined.

It worked on another test code i made so the problem is not from this part really but more likely from the rest of my code.

I couldn't even make this work:

.use(function(req, res, next) {
  console.log('test');
})

Nothing appears in the console.

So i wanted to know if something else in my code could possibly interfere with this or not be compatible because everything else is working fine:

// Setting up requirement
//----------------------------------
var path = require('path'),
    express = require('express'),
    app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server),
    ent = require('ent'),
    mongoose = require('mongoose'),
    crypto = require('crypto');

// Connection to the database
//----------------------------------
mongoose.connect('mongodb://localhost/alpha');
var db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
    db.db.collectionNames(function(error, names) {
        if (error) {
          throw new Error(error);
        } else {
          names.map(function(name) {
            console.log(name);
          });
        }
    });
});


// Setting up express for routing
//----------------------------------
app.set('port', 8080)
.set('views', path.join(__dirname, 'views'))
.set('view engine', 'jade')
.use(express.cookieParser())
.use(express.session({secret: 'xxxx'}))
.use(express.favicon())
.use(express.logger('dev'))
.use(express.bodyParser())
.use(express.methodOverride())
.use(app.router)
.use(express.static(path.join(__dirname, 'public')))

// Client variables
//----------------------------------
.use(function(req, res, next) {
    console.log('test');
})

// Routing
//----------------------------------

// Index -- can be called via / or /index or /home
.get(/^\/(index|home)?$/, function(req, res) {
    res.render('index', {title: 'Home'});
})

// Login
.post('/login', function(req, res) {
    var login = req.body.login,
    password = crypto.createHash('md5').update(req.body.password, 'utf8').digest('hex'),
    loginT = 'aaa',
    passwordT = crypto.createHash('md5').update('zzz', 'utf8').digest('hex');

    if(password == passwordT) 
        res.send({error: false});
    else
        res.send({error: true});
})

// Starting up the server
//----------------------------------
server.listen(app.get('port'), function() {
  console.log('Express server listening on port ' + app.get('port'));
});

I really can't figure out what is the issue here, again the rest of the code works perfectly, be it the mongoose or express parts (didn't test for socket.io yet on this code).

Thanks in advance..

1 Answer 1

1

Move your function to somewhere above .use(app.router).

EXPLANATION:

  • Express calls middleware (app.use functions) in the order they are added to the app until something doesn't call next().
  • app.router middleware checks for matching url routes and then uses that function, otherwise calls next().

Therefore, any middleware defined BELOW app.router will only be called if the current url doesn't match any defined routes. It's good to place the static files below the app.router so that a poorly named file doesn't take over a proper url, but that's not the behaviour you're looking for.

Sign up to request clarification or add additional context in comments.

2 Comments

I had already read that app.use needed to be called in a certain order but nowhere there was an example with the function call and it was not really clear to me in the end. My problem is now fixed, your answer was simple yet enlightening ; now i understand more all the app.use and also the need of next() (which i removed here to test and obviously my code was stuck in my function), thank you very much.
No problem! The documentation on it is a bit lacking. Express uses connect and doesn't bother documenting connect stuff, so to piece it all together you have to work weirdly backwards. That said, I really love express for how straightforward everything is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.