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
這意味着我必須爲所有人添加會話:req.session。爲什麼我不能使用res.locals? – shin
@shin對不起,我爲解決方案添加了一箇中間件解決方案。 – JohnnyHK
謝謝,現在有道理。 – shin