Following is my code for session setup:
import app from './server.js';
import dotenv from 'dotenv';
import mongoose from 'mongoose';
import session from 'express-session';
import {default as connectMongo} from 'connect-mongo';
dotenv.config();
const port = process.env.PORT || 8000;
const MongoURI = process.env.BLOG_DB_URI;
const MAX_AGE = process.env.MAX_AGE;
mongoose
.connect(MongoURI, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then((client) => {
const mongoDBstore = connectMongo.create({
mongoUrl: MongoURI,
client: client,
collection: "mySessions"
});
console.log('session: ' session);
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
store: mongoDBstore,
cookie: {
path: '/',
httpOnly: false,
maxAge: MAX_AGE,
sameSite: false
}
})
);
app.listen(port, () => console.log(`listening on port: ${port}`));
})
.catch((err) => console.log(err));
And below is my code for user login:
static async loginUser(req, res, next) {
try{
const user = await User.findOne({userName: req.body.userName});
!user && res.status(400).json('Please enter correct username');
const valid = await bcrypt.compare(req.body.password, user.password);
!valid && res.status(400).json('Invalid Password');
const sessUser = {
id: user._id,
userName: user.userName,
email: user.email
};
console.log('req.session: ' req.session);
req.session.user = sessUser;
res.status(200).json(sessUser);
} catch(err) {
res.status(500).json(`login error: ${err}`);
}
}
Now when I'm going over to my login route : '/api/user/login' and trying to log in an existing user, I'm getting the error:
login error: TypeError: Cannot set property 'user' of undefined
On printing the value of req.session it is showing as undefined. Can someone please give me some idea on what I might be doing wrong? Thanks in advance.
CodePudding user response:
The issue was due to the order in which I declared the middlewares.
app.use(session(...))
had to come before app.use('/api/users/login', function(...))
. Otherwise res.session
will remain undefined.