2012-12-30 45 views
2

我正在玩Node/Express 3.0。但我不確定如何獲得會話。特別是我不確定我是否正在使用routes/session.js中的以下內容。如何在Node/Express中將會話傳遞到視圖中?

app.use(function(req, res, next) { 
    res.locals.session = req.session; 
    next(); 
}); 

以下是更多的細節。

我有這個在app.js

var express = require('express') 
    , routes = require('./routes') 
    , http = require('http') 
    , path = require('path') 
    ; 

var app = express(); 

app.configure(function(){ 
    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.cookieParser('testtest')); 
    app.use(express.session({ 
    secret: 'testtest', 
    maxAge: 3600000 
    })); 
    app.use(app.router); 
    app.use(express.static(path.join(__dirname, 'public'))); 
}); 
... 
require ('./routes/session')(app); 
... 
http.createServer(app).listen(app.get('port'), function(){ 
    console.log("Express server listening on port " + app.get('port')); 
}); 

而且在路線/ session.js

module.exports = function(app) { 

    app.use(function(req, res, next) { 
    res.locals.session = req.session; 
    next(); 
    }); 

    app.get('/session/new', function(req, res) { 
    res.render('session/new', {title: "Log in"}); 
    }); 

    app.post('/session', function(req, res) { 
    if (users[req.body.username] && 
     users[req.body.username].password === req.body.password) { 
     req.session.user = users[req.body.username]; 
     res.redirect('/users'); 
     } else { 
     res.redirect('/session/new') 
     } 
    }); 

    app.del('/session', function(req, res, next) { 
    req.session.destroy(); 
    res.redirect('/users'); 
    }); 

}; 

我有這樣的觀點。

- if (session.user) { 

    p 
    span Hello  
    span= session.user.name 
    span= session 
    span ! 
    p 
    form(method="POST", action="/session") 
     input(type="hidden", name="_method", value="DELETE") 
     input(type="submit", value="Log out") 

- } else { 

    p 
    a(href="/session/new") Login 
    span  or  
    a(href="https://stackoverflow.com/users/new") Register 

- } 

但是,這不會拿起會話,並給出一個錯誤。

1| > 2| - if (session.user) { 3| 4| p 5| span Hello session is not defined 

回答

6

對於中間件的工作方式,你需要確保你的app.use調用安裝中間件您的來電app.use(app.router);之前完成。目前您是通過require('./routes/session')(app);調用後調用它:

require ('./routes/session')(app); 
app.use(app.router); 

要做到這一點,而不中間件,改變你的res.render電話在本地session變量傳遞,您希望可認爲:

app.get('/session/new', function(req, res) { 
    res.render('session/new', {title: "Log in", session: req.session}); 
}); 
+0

這意味着我必須爲所有人添加會話:req.session。爲什麼我不能使用res.locals? – shin

+0

@shin對不起,我爲解決方案添加了一箇中間件解決方案。 – JohnnyHK

+0

謝謝,現在有道理。 – shin

相關問題