I am using in my express app the message alert middleware connect-flash. I can find this middleware on github https://github.com/jaredhanson/connect-flash.
When i look at connect-flash source code, i really don't know, where the this.session object come from. Consider the connect-flash source code:
module.exports = function flash(options) {
options = options || {};
var safe = (options.unsafe === undefined) ? true : !options.unsafe;
return function(req, res, next) {
if (req.flash && safe) { return next(); }
req.flash = _flash;
next();
}
}
function _flash(type, msg) {
if (this.session === undefined) throw Error('req.flash() requires sessions');
var msgs = this.session.flash = this.session.flash || {};
if (type && msg) {
// util.format is available in Node.js 0.6+
if (arguments.length > 2 && format) {
var args = Array.prototype.slice.call(arguments, 1);
msg = format.apply(undefined, args);
} else if (isArray(msg)) {
msg.forEach(function(val){
(msgs[type] = msgs[type] || []).push(val);
});
return msgs[type].length;
}
return (msgs[type] = msgs[type] || []).push(msg);
} else if (type) {
var arr = msgs[type];
delete msgs[type];
return arr || [];
} else {
this.session.flash = {};
return msgs;
}
}
To implement in express, i have to include within the app.configure block. Consider the code
app.configure(function () {
//Other middleware
app.use(function (req, res, next) {
console.log(this.session);
next();
});
app.use(flash());
Look at my custom middleware, when i display this.session object, i got "undefined". Why is this.session in connect-flash working, i get overthere the session object, but not in my middleware. The callback pattern for create a middleware are exactly the same
(function (req, res, next) {
//Code
next();
}