Why can't I get the value of the session? - node.js

this is my code of app.js, and I save session in mongoDB.
const cookieParser = require('cookie-parser');
const cookieSession = require('cookie-session');
const session = require('express-session');
const mongoStore = require('connect-mongo')(session);
const db = mongoose.connect("mongodb://localhost/course");
app.use(cookieParser());
app.use(cookieSession({ //session
secret: "system",
store: new mongoStore({
mongooseConnection: db.connection,
collection: "sessions"
})
}))
when I want to get req.session.user, I get undefined.
but I save session when user login.
exports.fetchCourse = async (req, res) => {
console.log("session is: " + req.session.user);
if(req.session.user) {
const user = await User.findOne({_id: req.session.user._id}).populate("course");
console.log("course are: " + user.course.length);
res.status(200).send({
code: 1,
data: user.course,
msg: "获取全部课程"
})
}
}

You are using cookieSession instead of expressSsession.
according to the docs your code shall look similar to this (if you use express 4 and above):
const session = require('express-session');
const mongoStore = require('connect-mongo')(session);
const db = mongoose.connect("mongodb://localhost/course");
app.use(session({
secret: "system",
store: new mongoStore({
mongooseConnection: db.connection,
collection: "sessions"
})

Related

express-session middleware creates a new database which includes sessions collection. NodeJS-Express-MongoDB

I use express-session to store sessions in my database. It works fine on my local mongodb, but when it comes to MongoDB Atlas, the middleware creates a new database named test and places sessions collection in it. I want the sessions collection to be created in nodeblog_online db.
Thanks in advance.
app.js :
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const session = require('express-session');
const connectMongo = require('connect-mongo');
const dotenv = require('dotenv');
const conn = require('./db'); //to connect my database********
dotenv.config();
conn();
app.use(session({
secret: 'testo',
dbName: 'nodeblog_online',
resave: false,
saveUninitialized: true,
store: connectMongo.create({ mongoUrl: process.env.DB_URL })
}));
db.js (conn function)
const mongoose = require('mongoose');
const conn = () => {
mongoose.connect(process.env.DB_URL, {
dbName: 'nodeblog_online',
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => {
console.log('connected successfully.')
}).catch(err => {
console.log(`connection error: ${err}`)
})
}
module.exports = conn;
Try this:
app.use(session({
secret: 'testo',
resave: false,
saveUninitialized: true,
store: connectMongo.create({
mongoUrl: process.env.DB_URL,
dbName: 'nodeblog_online',
})
}));

how to pass the already running db connection into the mongo store for storing sessions

I am new to backend development so I am facing some problems.
I have used mongoose.connection() to connect my db into the server.
Now I want to store the user sessions into the database and for that I have used express-session andmongo-store for that. To create mongo-store instance, I have to again pass the database string and its other options to run a new db connection. Can I overcome this somehow ?
const express = require('express');
const mongoose = require('mongoose');
const session = require('express-session');
const passport = require('passport');
const cookieParser = require('cookie-parser');
const MongoStore = require('connect-mongo');
require('dotenv').config();
const app = express();
//Passport config
require('./config/passport');
// //Connect To DB
const dbOptions = {
useNewUrlParser: true,
useUnifiedTopology: true
}
//--------------Here I have created a connection with the database----------------------//
mongoose.connect(process.env.DB_String, dbOptions)
.then(() => { console.log("Connected to the databse....") })
.catch(error => console.log('Error While Connecting to db', error));
//Middleware to read the body of requests
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
//Express session middleware
app.use(session({
secret: process.env.Session_Secret,
resave: true,
//---------Here I am creating a new connection with the database for storing sessions--------//
store: MongoStore.create({
mongoUrl: process.env.DB_String,
mongoOptions: dbOptions,
collection: 'sessions'
}),
saveUninitialized: true,
cookie: {
maxAge: 1000 * 60 * 60 * 24
}
}));
//Passport middlewares
app.use(passport.initialize());
app.use(passport.session());
//Endpoints
app.use('/api/', require('./api/index'));
app.use('*', (req, res) => {
res.status(404).json({message: 'Route not found'});
})
//Listen to the port
app.listen(process.env.port, () => {
console.log(`app is listening on port ${process.env.port}`);
});
You should do:
store: Mongostore.create({
mongooseConnection: mongoose.connection
})
And if this doesnt work declare your mongostore like this:
const MongoStore = require('connect-mongo')(session);

exporting/using express-session in another file

What's the best/common way to use an express-session in other files? I have trouble integrating the session into my code. I was using auth tokens, but I would like to use sessions instead.
I defined session in my server.js:
const express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser('secret'));
app.use(session({
key: 'user_sid',
secret: 'secret',
resave: false,
saveUninitialized: false,
cookie: {
expires: 600000
}
}));
// stuff
module.exports = {app, session};
And it works fine! But When I try to use it in my userController.js:
var express = require('express');
var {session} = require('./../server');
module.exports.login = (req, res) => {
var body = _.pick(req.body, ['email', 'password']);
User.findByEmailAndPassword(body.email, body.password).then((user) => {
// console.log(req.session); // is undefined
res.render('dashboard.hbs');
}).catch((e) => {
res.status(400).send();
});
}
then req.session is undefined.
I know what I'm doing isn't right, obviously, but what's the right way to do it?
Thanks!
I think you don't have to export session at all, as you are telling your app to use it in server.js.
So the working fiddle should be looking like the following:
const express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser('secret'));
app.use(session({
key: 'user_sid',
secret: 'secret',
resave: false,
saveUninitialized: false,
cookie: {
expires: 600000
}
}));
// stuff
module.exports = app;
and your controller:
module.exports.login = (req, res) => {
var body = _.pick(req.body, ['email', 'password']);
User.findByEmailAndPassword(body.email, body.password).then((user) => {
// console.log(req.session); // is undefined
res.render('dashboard.hbs');
}).catch((e) => {
res.status(400).send();
});
}
I am considering that you are going to use this exported login function for a route, like
app.use('/login', require('yourCtrl.js').login);

req.session is undefined nodeJS

im trying to set up a session in NodeJS and use it in my /auth route after that but i'm getting undefined troubles with the session.
In the app.js :
const express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cors = require('cors'),
mongoose = require('mongoose'),
config = require('./config/DB');
const app = express();
const session = require('express-session')
const MongoStore = require('connect-mongo')(session);
mongoose.connect(config.DB, { useNewUrlParser: true }).then(
() => { console.log('Database is connected') },
err => { console.log('Can not connect to the database' + err) },
options
);
const db = mongoose.connection
const adUnitRoutes = require('./routes/adunit.route');
const userProfileRoutes = require('./routes/userprofile.route');
app.use('/adunits', adUnitRoutes);
app.use('/userprofile', userProfileRoutes);
app.use(session({
secret: 'my-secret',
resave: false,
saveUninitialized: true,
store: new MongoStore({ mongooseConnection: db })
}));
In the route :
userProfileRoutes.route('/authentification').post((req, res) => {
console.log('req session : ' + req.session.userId);
//here I got cant read property of userId because session is undefined
});
This happens because you are setting your routes before adding the middleware. Your handlers are essentially middleware so if they are added before session, your session has not been processed and added to the request yet.
Adding the routes after setting your middleware will make it work as expected.
See this minimized example:
const express = require('express');
const app = express();
const session = require('express-session');
app.get('/broken', (req, res) => {
console.log('req session : ' + req.session.userId);
res.write(String(req.session.userId));
req.session.userId = 1;
res.end();
});
app.use(
session({
secret: 'my-secret',
resave: false,
saveUninitialized: true
})
);
app.get('/ok', (req, res) => {
console.log('req session : ' + req.session.userId);
res.write(String(req.session.userId));
req.session.userId = 1;
res.end();
});
app.listen(8089);

Unable to use sessions in node.js

I developing login page.
If user successfully logs in , then I want to store user_Id into session variable,which I will be using to authenticate other pages.
App.js
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('passport');
var cookieParser = require('cookie-parser');
var session = require('express-session');
app.use(bodyParser.json());
app.use('/user', userRoutes);
app.use('/', index);
app.use(cookieParser());
app.use(session({
secret: "helloKey",
resave: false,
saveUninitialized: true,
store: new MongoStore({ mongooseConnection: mongoose.connection}),
cookie: { maxAge: 180 * 60 * 1000 }
}));
User router
var express = require('express');
var router = express.Router();
User = require('../models/user');
//Login User
router.post('/login', function (req, res) {
var user = new User(req.body);
User.login(user, function (err, user) {
if (err) {
res.sendStatus(500);
throw err;
}
if (!user) {
res.sendStatus(404);
return;
}
req.session.name = user.id;
res.json(user.id);
});
});
Problem is if I execute this code I am getting Cannot set property 'name' of undefined
What I am doing wrong?
Please Help.
Problem is that your routes are already setup before session so you have to reorder the code.
Move these lines
app.use('/user', userRoutes);
app.use('/', index);
Below the app.use(session) declaration.
app.use(session({
secret: "helloKey",
resave: false,
saveUninitialized: true,
store: new MongoStore({ mongooseConnection: mongoose.connection}),
cookie: { maxAge: 180 * 60 * 1000 }
}))

Resources