使用NodeJS设置会话变量

时间:2017-07-07 17:53:17

标签: javascript node.js session

在验证之后我想设置一个会话变量。目标是在每个视图上访问用户的id。

我使用快递和快递会话。 我的问题是,当我想访问会话变量时。 在使用它之前,我不知道它们是否是初始化。因为当我使用时:

if(req.session.username)

例如,我有一个错误:未定义用户名。

app.js:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cors=require('cors');

//var index = require('./routes/index');
//var users = require('./routes/users');
var UsersDB=require('./routes/UsersDB');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(cors());
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));

//app.use('/', index);
//app.use('/users', users);
app.use('/Users',UsersDB);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.use(function(req, res, next) {
	res.set({'Content-Type': 'text/plain; charset=utf-8;',
		'Access-Control-Allow-Origin': '*', 
		'Access-Control-Allow-Methods': 'GET, POST, DELETE, OPTIONS', 
		'Access-Control-Allow-Headers': 'X-PINGOTHER', 
		'Access-Control-Max-Age': '1728000'});
	next();
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

UsersDB.js:

var express = require('express');
var router = express.Router();
var Users=require('../models/Users');
var multer = require('multer');
var crypto = require('crypto');

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

var app = express();

app.use(cookieParser());
app.use(session({
    secret: "fd34s@!@dfa453f3DF#$D&W", 
    resave: false, 
    saveUninitialized: true, 
    cookie: { secure: false }
}));

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './uploads')
},
filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now() + ".png")
}
});

var upload = multer({ storage: storage }).single('avatar');

router.post('/login',function(req,res,next)
{
    upload(req, res, function (err) {
        if (err) {
      // An error occurred when uploading
            return
        }
    // Everything went fine
        console.log(req.body);
        var login = req.body.username;
        var pass = req.body.password;
        
        if(req.session.username) { 
            console.log(req.session.username);
        }
        else{
            req.session.username = "toto";
        }

        const hash = crypto.createHmac('sha256','YouOu').update(pass).digest('hex');
        Users.getUsersByEmail(login,function(err,rows)
        {
            if(rows == null){
                res.end("No such user");
                return;
            }
            if(rows[0].password != hash){
                res.end("Wrong pass")
                return;
            }
            else{
                res.end("Ok")
                return;
            }
        })
 
    })
});

module.exports=router;

Login.html:

<script type="text/javascript">
        $("form[name=loginform]").submit(function(event){
 
            //disable the default form submission
            event.preventDefault();
           
            //grab all form data  
            var formData = new FormData($(this)[0]);
           
            $.ajax({
              url:'http://localhost:3000/Users/login',
              type: 'POST',
              data: formData,
              async: false,
              cache: false,
              contentType: false,
              processData: false,
              success: function (returndata) {
                if(returndata == "Wrong pass") {
                  alert("wrong password");
                } else if(returndata == "No such user")
                {
                  alert("no such user");
                } else {
                   alert("Welcome");
                    window.location.href="index.html"
                }
               
              }
            });
           
            return false;
        });
        

      </script>

1 个答案:

答案 0 :(得分:2)

据我所知,问题是你在一个不会被使用的app模块上初始化UsersDB.js中的会话。尝试在app.js中初始化它。