Node.js Express.js Mongoose:不保存会话

时间:2015-08-04 15:37:43

标签: jquery node.js mongodb express mongoose

我最近想学习node.js。我刚刚设置了Phonegap项目,并且req.session未定义。 这是我的代码:app.js

c.select('div.input input').property("value", kv)

这是我的数据库模型和功能。 login.js

var express = require('express'),
routes = require('./routes'),
data = require('./routes/data'),
login = require('./routes/login'),
asignatura = require('./routes/login'),
http = require('http'),
cookieParser = require('cookie-parser'),
path = require('path'),
session = require('express-session');

var app = express();

app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(cookieParser());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.cookieParser());
app.use(session({cookieName: 'session',
                     secret: "secret",
                     resave: true,
                saveUninitialized: true}));
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.post('/signIn', login.signIn);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});

Index.ejs

var mongoose = require('mongoose');
var bcrypt   = require('bcrypt-nodejs');
var loginSchema = mongoose.Schema({
_id:String,
pass:String,
tipo:String
});
loginSchema.methods.generateHash = function(pass) {
return bcrypt.hashSync(pass, bcrypt.genSaltSync(8), null);
};

loginSchema.methods.verifyPassword = function(pass) {
return bcrypt.compareSync(pass, this.login.pass);
};

  var login = mongoose.model('login', loginSchema);

 exports.signIn = function(req, res){
 var dniNum = req.body.dniNum;
 var password = req.body.password;

login.find({_id: dniNum, pass: password}, function(err, data){
    res.send({err: err, data: data});
    console.log(data);
    console.log(err);
   console.log(req.session);
   var user = req.session.data;
});

SignIn.js

<body>
 <div class="ui-header ui-bar-inherit" data-role="header">
    <h1 class="ui-title">Login</h1>
 </div>
   <div data-role="content" class="ui-content">
    <div>
     <h5>Cédula:<input type="text" name="dni" id="inputdniNum" placeholder="Cedula"/></h5>

     </div>
    <div>
        <h5>Contraseña</h5>
        <input type="password" id="inputPassword" placeholder="Password"/>
    </div>
       <br>
  <label id="errMsg" class="control-label"></label>

  <br>
     <div>
       <button id="signIn" type="submit" >Ingresar</button> 

    </div>
       </div>
</body>

这在我的控制台中显示为错误, req.session 未定义

    $(document).ready(function(){
      $("#signIn").click(function(){
        var dniNum = $("#inputdniNum").val();
        var password = $("#inputPassword").val();

     if(dniNum == '' || password == ''){
        $("#form").addClass('has-error');
        $('#errMsg').html('El dni o la contraseña no puede estar vacia')
     } 
     else {

        var data = {
            dniNum: dniNum, 
            password: password
        };
        $.ajax({
            type: "post",
            url: "/signIn",
            data: data
        }).success(function (data, textstatus){
            if(data.data == 0){

           // if(data.dniNum !== dniNum && data.pass !== password){
                $("#form").addClass('has-error');
                $('#errMsg').html('El dni o la contraseña es incorrecta');
            }
            else {
                sessionStorage.setItem('signedInUser', JSON.stringify(data.data));
                    sessionStorage.getItem('signedInUser');
                    window.location.assign("/alumno_principal");

            }
        }).error(function (err, textStatus){
            alert(err + textStatus);
        })
    }
})

});

2 个答案:

答案 0 :(得分:2)

您可以使用护照模块,这将负责身份验证过程

var passport = require('passport');

app.use(passport.initialize());      // Initialize PassportJS
app.use(passport.session());     

定义本地策略local_strategy.js

var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var models  = require('models');

function PassportLocalStrategy() {

  LocalStrategy.call(this, { usernameField: 'email' },     this.verifyUser.bind(this));

  passport.serializeUser(function(user, done) {
  done(null, user.id);      
  passport.deserializeUser(this.get.bind(this));      
}

PassportLocalStrategy.prototype.get = function(id, done) {
    models.User.find({ where: { id: id } }).then(function(user){ done(null,     user.dataValues) });
};

PassportLocalStrategy.prototype.verifyUser = function(email, password, done) {
models.User.find({ where: { email: email } }).then( function(user){ user;
  done(null, user.dataValues);
})
};

module.exports = PassportLocalStrategy;

答案 1 :(得分:0)

passport js是处理node.js express.js应用程序会话的更好选择。

此处提供完整的文档和配置以及示例 -

https://github.com/jaredhanson/passport