I have an app that is already working. The problem began when I coded the session part of it. The server hangs when finds this lines of code in the controller:
req.session.save(() => {
req.session.loggedIn = true;
});
The user-routes.js controller is:
const router = require('express').Router();
console.log(__filename);
router.get('/login', (req, res) => {
res.render('login');
});
router.post('/verify', (req, res) => {
try {
// HERE *********************************************************************
req.session.save(() => {
req.session.loggedIn = true;
});
const messages = {};
res.render('dashboard', {messages, loggedIn:req.session.loggedIn},);
} catch (e) {
}
});
router.get('/newUser', (req, res) => {
res.render('newUser');
});
router.post('/saveUser', (req, res) => {
res.render('dashboard');
});
module.exports = router;
and my server.js is:
const root = require('app-root-path')
const express = require('express');
const path = require('path');
const exphbs = require('express-handlebars');
const session = require('express-session');
const SequelizeStore = require('connect-session-sequelize')(session.Store);
const sequelize = require('./config/connection');
const app = express();
const PORT = process.env.PORT || 3000;
const routes = require('./controllers/index');
const configSession = {
secret: 'this is a secret',
cookie: {maxAge: 86400,},
resave: false,
saveUninitialized: true,
store: new SequelizeStore({db: sequelize}),
};
app.use(express.json());
app.use(express.static(root path.sep 'public'));
app.use(express.urlencoded({extended: true}));
app.use(routes);
app.use(session(configSession));
const hbs = exphbs.create();
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
const run = async () => {
//const sequelizeResult = await sequelize.sync({force: true});
//console.log("---> sequelizeResult :" (sequelizeResult));
await app.listen(PORT, () => {
console.log('Server listening on port %j', PORT);
});
}
//RUN
run();
I am using MySQL. I stopped the server, dropped the db tables, create and seed them again.
What could be the problem? Your help is greatly appreciated.
CodePudding user response:
Sequelize needs to sync the tables (and add the session table) when the server starts. I am uncommenting the line where sequelize.sync() is called
const run = async () => {
const sequelizeResult = await sequelize.sync({force: true});
//console.log("---> sequelizeResult :" (sequelizeResult));
await app.listen(PORT, () => {
console.log('Server listening on port %j', PORT);
});
}
That solved the problem.