在快速框架中的会话中得到奇怪的错误

beN*_*erd 29 node.js express

我是新来的表达框架,这是我在server.js文件中的内容:

// Module dependencies.
var application_root = __dirname,
express = require( 'express' ), //Web framework
path = require( 'path' ), //Utilities for dealing with file paths
mongoose = require( 'mongoose' ); //MongoDB integration

//Create server
var app = express();

// Configure server
app.configure( function() {

app.use( express.bodyParser() );
app.use( express.methodOverride() );
app.use( app.router );
app.use(express.session({secret:'thisismysupersecret'}));
app.use( express.static( path.join( application_root, 'site') ) );
app.use( express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.post("/verifyLogin",function(request,response){
var usr=request.body.username;
var pass=request.body.password;
//request.session.email=usr;
response.redirect('dashboard');
});

//Start server
var port = 3000;
app.listen( port, function() {
console.log( 'Express server listening on port %d in %s mode', port, app.settings.env);
});
Run Code Online (Sandbox Code Playgroud)

当我导航到localhost:3000时,我收到此错误

500 TypeError:无法读取undefined的属性'connect.sid'

哪里出了问题?

rob*_*lep 75

你错过了cookieParser中间件:

...
app.use( express.cookieParser() );
app.use(express.session({secret:'thisismysupersecret'}));
...
Run Code Online (Sandbox Code Playgroud)

(因为会话是使用cookie实现的).

  • 实际上,我错了:`app.use(app.router)`应该在`app.use(express.session(...))`之下,这就够了.原因是中间件按添加顺序调用,如果要在路由中使用会话,则需要在路由器之前添加会话中间件,否则会话中间件永远不会被调用(因为处理路由的中间件已添加更早). (2认同)