微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

会话无法与Express-Session和Connect-Session-Sequelize保持一致

如何解决会话无法与Express-Session和Connect-Session-Sequelize保持一致

我正在使用Sequilize库与MysqL数据库连接。一切正常。但是,该会话并不会在每次浏览器重新加载时都持续存在,新会话将以空的userId存储在数据库中,有时甚至会超过一个。我不知道为什么。我正在通过快递服务器提供我的 VUE SPA,它的运行正常。

我调查了StackOverflow,一些解决方案指向cors事物,但是我仅对VUE和Node使用一个端口,因此应该没有问题。非常感谢您的帮助。

下面是代码以及显示会话数据库中行的一些图像。

这是应用程序初始化的代码

const bodyParser = require('body-parser')
const cors = require('cors')
const cookieParser = require('cookie-parser')
const passport = require('passport')
const GoogleStrategy = require('passport-google-oauth20')
const session = require('express-session')
// initalize sequelize with session store
var SequelizeStore = require("connect-session-sequelize")(session.Store);

const User = require("./models/User")

const Keys = require("./config/Keys")
const Db = require("./config/db")


module.exports = new class {

    initialize(app) {
      app.use(bodyParser.json());
      app.use(bodyParser.urlencoded({ extended: true }));
      app.use(cookieParser(Keys.secret));

      // passport

      /*
      Stores information in the cookie when the user is created
      */
      passport.serializeUser(function(user,cb) {
        // console.log("this is the id which is getting used for serializing "+user.id);
        cb(null,user.id);
      });

      /*
      Extract information from cookie when logged in user sends the request
      */
      passport.deserializeUser(function(id,done) {

        User.findByPk(id)
        .then(user => {
          if(user) {
            done(null,user);
          } else {
            done(null,null);
          }
        })
        .catch(err=>{
          done(null,null);
        })

      });

      // Google OAuth

      passport.use(
        new GoogleStrategy({
          clientID: Keys.google.client_id,clientSecret: Keys.google.client_secret,callbackURL: '/login/google/return'
        },(accesstoken,refreshToken,profile,done) => {
          User.findAll({where: {email: profile._json.email}})
          .then(user => {
            if(user.length > 0) {
              done(null,user[0]);
            } else {
              User.create({
                email: profile._json.email,emailVerified: profile._json.email_verified,roles: 'user'
              })
              .then(result=> {
                done(null,result);
              })
              .catch(err => {
                console.log("err");
                console.log(err);
              })
            }
          }) 
          
        })
      )

     function extendDefaultFields(defaults,session) {
       let r = {
        data: defaults.data,expires: defaults.expires
      };
       if(session.passport) {
         if(session.passport.user) {
          r.userId = session.passport.user;
         }
       }
      
        return r;
      }

      var myStore = new SequelizeStore({
        db: Db,table: "Session",extendDefaultFields: extendDefaultFields,});
      
      // configuring session
      app.use(
        session({
          secret: Keys.secret,store: myStore,resave: false,// we support the touch method so per the express-session docs this should be set to false
          proxy: false,// if you do SSL outside of node.
          cookie: {secure: false}
        })
      );  

      app.use(passport.initialize());
      app.use(passport.session());  
 
    }

}

这是app.js文件代码

require('dotenv').config();
const express = require('express')
const app = express()
let ejs = require('ejs');
const auth = require("./auth.js");
const siteConfig = require('./config/site.js');
const routes = require('./server-routes.js');
const db = require("./config/db.js")

async function ignite() {

    try {
        if (!process.env.MSG) {
          throw new Error("\nEnvironment variables are not working.\n")
        }

        db.authenticate()
        .then(() => console.log("connectedd"))

        auth.initialize(app);
        
        app.use('/',routes);
        console.log("request going to vue app");

        // Handle production
        if(process.env.NODE_ENV === 'development') {
          //static folder
          app.use(express.static(__dirname + '/public'));

          // handle SPA (Single Page Application)
          app.get(/.*/,(req,res) => {
            res.sendFile(__dirname + '/public/index.html');
          })
        }

        app.listen(siteConfig.port,() => {
            console.log(`ExamByPass server is running on ${ process.env.PORT || siteConfig.port }!`);
        });

    } catch (e) {
        console.log("FATAL IGNITION ERROR",'\n',e);
    }

}

ignite();

click here to see the public folder

click here to see the image showing rows in session table

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?