error with express and connect-redis on store option - node.js

app.engine('html', ejs.renderFile)
.set("views", __dirname + '/views')
.use("/public", express.static(__dirname + '/public'));
/*********************************************************************/
app.use(cookieParser());
app.use(session({
store: new RedisStore({
host: "127.0.0.1",
port: "3636"
}),
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}));
app.use(function(req, res, next) {
var userSession = req.session.userSession;
if (!userSession) {
userSession = req.session.userSession = '';
}
next();
});
/************************************************************************/
server.listen(8080);
app.get('/', function(req, res) {
res.render('index2.html', {
infoUser: req.session.userSession
});
})
.use(function(req, res, next) {
res.redirect('/');
});
console shows me :
TypeError: Cannot read property 'userSession' of undefined.
I'm sure this error is caused by 'RedisStore' object but i don't know why and i don't know how the fixed ?
Have I any mistakes?
help me please !!!

The problem is in your RedisStore config. The port setting should be a number, like this:
app.use(session({
store: new RedisStore({
host: "localhost",
port: 3636
}),
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}));
If that doesn't fix it you should also make sure 3636 is the correct port. Redis uses 6379 by default.

Related

MongoStore, Atlasdb return the mongoUrl and ClientPromise

I am getting error while trying to save session on mongodb. Here is my code.
//MIDDLEWARE FUNC
app.use(methodOverride('_method',{methods: ['POST','GET']}))
app.use(Express.static(path.join(__dirname, 'public')))
app.use(Express.urlencoded({extended:true}))
app.use(Express.json())
app.use(session({
secret: 'my_keyboard_cat',
resave: false,
saveUninitialized: true,
store: MongoStore.create({
mongoUrl: process.env.DB_URI,
dbName: 'sessions'
})
}))
app.use(flash())
app.use((req,res,next) => {
res.locals.flashMessages = req.flash()
next()
})
and error is : Assertion failed: You must provide either mongoUrl|clientPromise|client in options
/app/node_modules/connect-mongo/build/main/lib/MongoStore.js:119
throw new Error('Cannot init client. Please provide correct options')
Error: Cannot init client. Please provide correct options

How to send cookies to client from node/express server?

I am having the hardest time sending cookies from my nodejs server to my browser. Below is my index.js (server side) code:
app.use(express.json());
app.use(express.urlencoded({ extended: true }))
app.use(
cors({
origin: "http://localhost:3000",
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
credentials: true
})
);
let port = process.env.PORT;
if (port == null || port == "") {
port = 5000;
}
mongoose.connect(process.env.ATLAS_URI).then(console.log("MongoDB Connection Success")).catch(err => console.log("MongoDB Connection Failed" + err))
app.use(session({
secret: 'random secret',
resave: false,
saveUninitialized: false,
// store: MongoStore.create({ mongoUrl: process.env.ATLAS_URI }),
cookie: {
expires: 7 * 24 * 6 * 60 * 1000,
secure: false,
},
}));
app.use(cookieParser())
app.use(passport.initialize())
app.use(passport.session())
app.use("/auth", auth)
I know a cookie is being created when i authenticate a user because if i uncomment out the store in app.use(session({...}) i see session IDs and cookies in my mongodb. But how can I send it to the browser?
try this config for the session options.
my version of express-session is "^1.17.2"
app.use(session({
name: 'random name',
resave: false,
saveUninitialized: false,
secret: 'random secret',
store: MongoStore.create({
mongoUrl: config.DatabaseUrl,
ttl: 14 * 24 * 60 * 60 // = 14 days. Default
})
}));
if this config does not work, check your passport authenticate function that set session true like the below example :
passport.authenticate('local.register', {session: true}, (err, user): void => {
// When res has an Error
if (err) return res.redirect('/auth/register');
return res.redirect('/');
})(req, res);

express session is not working with vuejs and axios

Session initialize in express.js also used passport.js for local-authentication which is working fine. But the session/cookie is not working
app.use(serveStatic(__dirname + '../../dist'));
mongoose.connect(config.database, function(err){
if(err) console.log(err);
console.log('Connected to DB');
})
app.use(cors({
origin:['http://localhost:8080'],
credentials: true // enable set cookie
}));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.urlencoded({ 'extended': 'false' }));
// required for passport
require('./config/passport')(passport); // pass passport for configuration
app.use(session({
secret: config.secret,
resave: true,
saveUninitialized: true,
cookie: { secure: true }
}));
// session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
Get request with axios is below
axios.get(this.url + '/user', {withCredentials: true})
.then(response => {
console.log(response);
})
.catch(e => {
this.errors.push(e)
})
Refer tutorial to store sessions or cookies using passport.js and express.js
app.use(session({
secret: config.secret,
resave: true,
saveUninitialized: true,
cookie: { secure: true }
}));
instead of this try:
app.use(express.session({
secret: config.secret,
resave: true,
saveUninitialized: true,
cookie: { secure: true }
}));
app.use(passport.session());

Why index.html is rendered in Node.js

I have a handler for '/', which redirects to /login.html.
However, even though i'm explicitly calling to redirection, the page that is rendered is STILL index.html.
it's pretty lame behaviour, since I'm expecting A and gets B.
How can I solve it?
var app = express();
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());
MW:
app.use('/', (req, res, next) => {
if (req.user) {
next();
} else {
res.redirect('/login.html');
}
});
app.post('/login',
passport.authenticate('local', {
successRedirect: '/index.html',
failureRedirect: '/login.html'
})
);

Node Express Session is not working. Getting req.session.user undefined for next request

app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(express_session({
secret: 'abcdefg',
proxy: true,
resave: true,
saveUninitialized: true,
}));
app.post("/login", function(req, res, next) {
var session = req.session;
session.user = 'dadsvadsvhaha';
});
Here is my code. I have used this previously in the same way. But now its not working, unable to figure it out.
I tried following and works fine for me. It just increments value to request.session.views variable if existing or sets request.session.views = 1
// Use the session middleware
app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}))
// Access the session as req.session
app.get('/', function(req, res, next) {
var sess = req.session
if (sess.views) {
sess.views++
res.setHeader('Content-Type', 'text/html')
res.write('<p>views: ' + sess.views + '</p>')
res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>')
res.end()
} else {
sess.views = 1
res.end('welcome to the session demo. refresh!')
}});
Which version of Node.Js are you using?

Resources