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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.