如何在expressjs(4.0)中创建会话?
我在links
中完全一样var session = require('express-session');
/* session */
app.use(session({ secret: '1s2sd25asd7asd5asd7f4f1f'}))
然而它会出错?
TypeError: Cannot read property 'connect.sid' of undefined
如何在expressjs中创建会话?我一直在尝试创建3天的会话。
答案 0 :(得分:4)
在快递4中,像这样创建会话
var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
var session = require('express-session');
您必须在会话
之前使用cookieParserapp.use(cookieParser())
app.use(session({secret: 'MySecret'}));
答案 1 :(得分:1)
完整代码:
var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var app = express();
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.use(session({secret: 'ssshhhhh'}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
var sess;
app.get('/',function(req,res){
sess=req.session;
//Session set when user Request our app via URL
if(sess.email)
{
/*
* This line check Session existence.
* If it existed will do some action.
*/
res.redirect('/admin');
}
else{
res.render('index.html');
}
});
app.post('/login',function(req,res){
sess=req.session;
//In this we are assigning email to sess.email variable.
//email comes from HTML page.
sess.email=req.body.email;
res.end('done');
});
app.get('/admin',function(req,res){
sess=req.session;
if(sess.email)
{
res.write('
<h1>Hello '+sess.email+'</h1>
');
res.end('<a href="+">Logout</a>');
}
else
{
res.write('
<h1>Please login first.</h1>
');
res.end('<a href="+">Login</a>');
}
});
app.get('/logout',function(req,res){
req.session.destroy(function(err){
if(err){
console.log(err);
}
else
{
res.redirect('/');
}
});
});
app.listen(3000,function(){
console.log("App Started on PORT 3000");
});
请在此处阅读:http://codeforgeek.com/2014/09/manage-session-using-node-js-express-4/