var express = require('express') ,
routes = require('./routes') ,
user = require('./routes/user') ,
http = require('http') ,
path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
添加session功能
//第一种用 MongoSessionStore(这个是使用session数据库的,需要安装MongoSessionStore模块,该模块依赖mongodb模块,所以也要安装mongodb模块)
//地址:https://github.com/lodengo/MongoSessionStore
var MongoSessionStore = require('MongoSessionStore')(express);
app.use(express.cookieParser('your secret here'));
app.use(express.session({ cookie: { maxAge: 2 * 60 * 1000 } , secret: "session secret" , store: new MongoSessionStore({ mongodb_connection_url: "mongodb://127.0.0.1:27017/test", mongoclient_connect_options: {} }) }));
//第二种 使用内存
app.use(express.cookieParser('likeshan'));
app.use(express.session({ secret: "andylau" }));
//第三种 使用connect-mongo(需要安装connect-mongo模块,该模块依赖mongodb模块,所以也要安装mongodb模块)
var MongoStore = require('connect-mongo')(express);
app.use(express.cookieParser('andylau'));
app.use(express.session({ secret: 'andylau', store: new MongoStore({ //db:'test' url: "mongodb://127.0.0.1:27017/test" }) }));
//第一种和第三种是比较重量级的,因为是用到数据库
//而第二种是比较轻量级的,对于小型的网站比较适合
app.use(app.router);//注意这个放置的顺序很重要,不要放在session之前,要放在session之后,否则会提示cannot set property 'name' of undefined
// development only
if ('development' == app.get('env'))
{
app.use(express.errorHandler());
}
app.get('/test', function (req, res) {
req.session.name = 'andylau';
res.send(req.session);
console.log(req.session.name);
});
http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });
From: http://blog.sina.com.cn/s/blog_62fda93c0101h3ex.html