在视图中访问Express Session变量

时间:2016-01-06 13:01:27

标签: node.js express express-session

我正在尝试访问EJS视图中的会话变量。但是不能那样做 以下是代码

var express=require('express');
var mongoose=require('mongoose');
var db=require('./models/db.js');

var routes=require('./routes/route.js');
var user=require('./routes/user.js');
var bodyParser=require('body-parser');

var session=require('express-session');
var cookieParser=require('cookie-parser');

mongoose.connect('mongodb://localhost/test');

var app=express();

app.set('view engine','ejs');

app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use(cookieParser());
app.use(session({secret:"qazwsxedcrfvtgbyhnujm"}));


app.get('/',routes.home);
app.get('/register',routes.register);
app.post('/createUser',user.doCreate);
app.get('/login',routes.login);
app.post('/authenticate',user.login);


var port = process.env.PORT || 3000;

var server=app.listen(port,function(req,res){
    console.log("Catch the action at http://localhost:"+port);
});

这是登录处理程序

    exports.login=function(req,res){

    var username=req.body.username;
    var password=req.body.password;

    User.findOne({username:username}, function(err,user){

      if(err){
        console.log("Error : Please enetr valid username and password");
        res.redirect("/login");
      }

     user.comparePassword(password,function(err,isMatch){
       if(isMatch && isMatch==true){
         console.log("Authentication Suucessfull");
         req.session.username=user.username;
         res.render("/",{username:req.session.username});
       }else{
         console.log("Authentication UnSuucessfull");
         res.redirect("/login");
       }

     });

    });
  }

在EJS视图中,我尝试打印登录处理程序

设置的用户名
<div id="page-content-wrapper">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-lg-12">
                        <h1>Awesome</h1>
                        <% if( typeof(username) !== 'undefined' ) { %>
                        <h1><%=username%></h1>
                        <%}%>
                        <p>This template has a responsive menu toggling system. The menu will appear collapsed on smaller screens, and will appear non-collapsed on larger screens. When toggled using the button below, the menu will appear/disappear. On small screens, the page content will be pushed off canvas.</p>
                        <p>Make sure to keep all page content within the <code>#page-content-wrapper</code>.</p>
                        <a href="#menu-toggle" class="btn btn-default" id="menu-toggle">Toggle Menu</a>
                    </div>
                </div>
            </div>
        </div>

我在这里缺少什么?

0 个答案:

没有答案