无法在会话快速js中保存数据

时间:2019-11-02 17:51:51

标签: node.js express session express-session

我的登录路线:

router.post('/login', function (req, res) {

          var email=req.body.email;
          var password=req.body.password;
          var session=req.session;

          User.findOne({ email: req.body.email }, function(err, user) {


              bcrypt.compare(password, user.password, function( err,data) {

                if(data) {
                  req.session.userid = user._id
                  req.session.save(function() {
                    if(req.session.userid){
                      console.log(req.session.userid);
                      res.redirect("/admin");
                    }else{
                      res.json( 'no data in session' );
                    }
                  });


                  }else{


                    res.redirect('/register/login');
                  }
              });

          });





      });

打印控制台日志:

5db87e8a09509d1d84e56d45

但是当重定向/ admin路由时:

router.get('/admin',function (req, res,next) {

  var session=req.session;
  console.log(session);


    } );

仅打印:

Session {
  cookie:
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true,
     secure: true } }

我无法理解会话为何无法获取数据或保存数据。 所以我该如何在会话节点js中保存数据。 我也使用res.save()。但是保存掉。 我不使用任何软件包进行身份验证登录。 为了理解我的配置,我还添加了我的app.js文件。 我的app.js:=>

var express = require('express');
var path = require('path');
var app = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var session = require('express-session');
var fileUpload = require('express-fileupload');
var cookieParser = require('cookie-parser')
const { check, validationResult } = require('express-validator');
var nodemailer = require('nodemailer');
// app.use( express.static( "public" ) );//for image link public folder
// var expressValidator = require('express-validator');
// var config = require('./config/database');

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

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('connect mongodb');

});

// Express validator middleware
// app.use(expressValidator({
//     errorFormatter: function(param, msg, value) {
//         var namespace = param.split('.')
//         , root    = namespace.shift()
//         , formParam = root;

//       while(namespace.length) {
//         formParam += '[' + namespace.shift() + ']';
//       }
//       return {
//         param : formParam,
//         msg   : msg,
//         value : value
//       };
//     }
//   }));

//express message middleware
app.use(require('connect-flash')());
app.use(function (req, res, next) {
  res.locals.messages = require('express-messages')(req, res);
  next();
});

// set the view engine to ejs
app.set('views', path.join(__dirname, 'views')); 
app.set('view engine', 'ejs');

///public folder
app.use(express.static(path.join(__dirname, 'public')));

//express file upload middleware
app.use(fileUpload());
//cookie parser middleware
app.use(cookieParser())
//body parser middleware
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

// express sesson  middleware
app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: true }
  }))


  //route declair heree
var home=require('./routes/home');
var admin=require('./routes/admin');
var register=require('./routes/register');


//home route
app.use('/',home);
//admin route
app.use('/admin',admin);
//register route
app.use('/register',register);



//header category list
var Category=require('./models/category');


Category.find(function (err, categories) {
  if (err) {
      console.log(err);
  } else {
      app.locals.categories = categories;

  }
});


///header category list

var port = 3000;
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
``

1 个答案:

答案 0 :(得分:0)

localhost中保留cookie: { secure: false}。因为,如果您保留ture,则浏览器将收到HTTPS请求。选中here

另一件事,如果您使用express版本v4.16.0或更高版本,则不需要body-parser模块。选中herehere