I am trying to set up session variables that would persist between routes.
Problem is, that doesn't seem to happen. When I make a post request, the session variable is updated accordingly - however when trying a different get route via postman (and checking console output), the variable is empty
Here's the code:
const express = require('express')
const session = require('express-session')
const bodyParser = require('body-parser')
const app = express()
app.use(session({
secret: 'test one',
resave: false,
saveUninitialized: true,
name: "mycookiesession",
cookie: { secure: false }
}))
let mySession
app.use(function (req, res, next) {
mySession = req.session
mySession.basket = []
next()
})
app.get('/basket', function (req, res) {
console.log(mySession.basket)
res.send(mySession.basket)
})
app.post('/basket/add', function (req, res) {
mySession.basket = [0, 1, 2]
console.log(mySession.basket)
res.send('null')
res.status(201).end()
})
app.listen(3000, function () {
console.log('Example app listening')
})
What am I doing wrong? I just need to see the value added to the basket by post:basket/add when retrieving the var in the get:basket route
Cheers
You have a middleware the sets basket = [] in your session for every incoming request. This middleware is executed for every request, because the app.use(function ...) command does not specify a path.
Related
I am just starting to learn how to use cookies with node and express and I would like some help with getting this to work. I tried to follow the expressjs/session tutorial on GitHub, however I am getting req.session as undefined, so I am unable to set or get any values.
My goal is to save the first and last name of a user to a cookie so that an input field will auto populate. I'm not sure if I need to use cookie-parser as well or if express-session can handle that alone. I'm not sure of how to proceed as I am new to cookies and express-session.
All help is appreciated! Thanks in advance.
Code
let express = require('express');
let app = express();
let credentials = require('../modules/credentials.js');
let session = require('express-session');
let sessionOptions = {
secret: credentials.cookieSecret,
cookie: {
maxAge:269999999999
},
saveUninitialized: true,
resave:true
};
if (app.get('env') === 'production') {
app.set('trust proxy', 1);
sessionOptions.cookie.secure = true;
}
else {
sessionOptions.cookie.secure = false;
}
app.use(session(sessionOptions));
let router = express.Router();
app.use(router);
let request = require('request');
let db = require('../modules/queries');
let bodyParser = require('body-parser');
let cookieParser = require('cookie-parser');
// app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
router.get('/me', function(req, res, next) {
console.log('req.session: '+req.session);
let firstName = req.session.firstName;
let lastName = req.session.lastName;
if (firstName && lastName) {
res.render('student/me.jade', {firstName, lastName});
}
else {
res.render('student/me.jade', { firstName: '', lastName: ''});
}
});
router.post('/api/me', function(req, res, next) {
let firstName = req.body.firstName;
let lastName = req.body.lastName;
// session.firstName = firstName;
// session.lastName = lastName;
req.session.firstName = firstName;
req.session.lastName = lastName;
console.log('session.firstName: '+session.firstName);
db.addEvent(req, res, next);
});
module.exports = router;
Once you mount a router onto an Express app, any subsequently declared middleware on that app won't get called for any requests that target the router.
So if you have this:
app.use(router)
app.use(session(...));
The session middleware won't get called for any requests that get handled by router (even if you declare the routes that the router should handle at some later point). For that, you need to change the order:
app.use(session(...));
app.use(router);
An additional issue is that you're exporting router, which should probably be app (which is the instance that "holds" all the middleware, routers, etc):
module.exports = app;
To get session data
first , You have to initialize express-session with
app.use(session({ resave: true ,secret: '123456' , saveUninitialized: true}));
then When you want to put something in the session
req.session.firstName = 'Aniruddha';
req.session.lastName = 'Chakraborty';
Then you can check without errors
console.log('req.session: '+req.session.firstName);
Note: This is express-sessions work!
This problem occurred with me while trying to maintain req.session object in my app. I was setting req.session.user in a login route, but was not able to get the same outside that route.
console.log(req.session)
// undefined
Since there was no use of cookie in my app, I removed it.
Before removing cookie variable:
app.use(
session({
resave: false,
saveUninitialized: true,
secret: "anyrandomstring",
cookie: { secure: true},
})
);
After removing cookie variable:
app.use(
session({
resave: false,
saveUninitialized: true,
secret: "anyrandomstring",
})
);
This resolved my issue. And now I was able to access req.session from anywhere in the app.
console.log(req.session)
/* Session{
......
......
}
*/
Note: This issue might also occurs if you have initialized app.use(session({...})) at bottom of the file. Try to bring it to the top.
Why this happens: Click here
You will also see req.session === undefined if your Redis connection is invalid or missing!
I don't see anywhere in your code where connection info is being passed when configuring the session.
Another reason why this might happen is if you're making requests from a different URL. Make sure your app is running on the same URL as your Express back-end.
I am developing a Shopify App in node.js. I am using different Shopify webhooks for different actions. similarly for a specific scenario I need to use session value while I am getting response from Shopify API. So in this scenario the session is not working for me. Please have a look on below code.
My code in index.js
const express = require('express');
const app = express();
var session = require('express-session');
app.set('trust proxy', 1); // trust first proxy
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: {
httpOnly: false,
secure: true,
maxAge: 60000
}
}));
//Set the session
app.get('/check_timewindow_orders', function (req, res, next) {
req.session.delvy_date = query.date_select;
});
app.use(function (req, res, next) {
res.locals.delvy_date = req.session.delvy_date;
next();
});
I get the session value in app.get and app.post.
app.get('/order_created_get', function (req, res) {
console.log(req.cookies.delDate);
// It display the value store in session.
});
But I cannot get the session value when I get the post from shopify Order Create Webhook API.
app.post('/order_created', function (req, res) {
console.log(req.cookies.delDate); // It display Null.
});
You are not actually using the session.
You need to add it as middleware:
app.get('/check_timewindow_orders', session, function(req, res, next){
req.session.delvy_date = req.query.date_select;
});
app.use(session, function(req, res, next) {
res.locals.delvy_date = req.session.delvy_date;
next();
});
i have a some problem
i'm using express-session middleware in my app
it work
but
It did not work on any particular router.
my code is follows
//app.js
app.use(session({
secret: 'D$YTRH#%#$#^$#YR',
resave: false,
saveUninitialized: true,
}))
//assign session in outside
app.get(/*, (req, res, next)=>{
req.session.outSide = "outSideBlah"
next()
}
//my session Check middleware
app.get('/*', (req, res, next)=>{
console.log(req.session._inSide)
console.log(req.session._outSide)
next()
}
const auth = require('./routes/auth.js')(express)
app.use('/auth', auth)
//auth.js (my router)
//assign session in router ( inside)
module.exports = (express) => {
const auth = express.Router()
auth.post('/login', (req, res)=>{
req.session._inside = 'insideBlah' //Assign a session here
............some auth code ......
}
return auth
}
after login
in my session Check middleware
console.log(req.session.inSide) // undefined
console.log(req.session.outSide) // "outSideBlah"
Even though I assigned req.session.inSide in auth.js
req.session.inside is undefined
What is the problem?
Why can not I access a session assigned by my router (auth.js)?
somebody help me.. thank you...
Also I think you should use * instead of /*.
This is my code:
const functions = require('firebase-functions');
const express = require('express');
const session = require('express-session');
const FirebaseStore = require('connect-session-firebase')(session);
const firebase = require('firebase-admin');
const cookieParser = require('cookie-parser');
const ref = firebase.initializeApp(
functions.config().firebase
);
const app = express();
app.use(cookieParser());
app.set('trust proxy', 1);
app.use(session({
store: new FirebaseStore({
database: ref.database()
}),
secret: 'abigsigrettotheseeiosnofthmbiith765huig',
resave: true,
saveUninitialized: true,
cookie: { maxAge: 60000 }
}));
app.get('/', function(req, res, next) {
console.log(req.session);
req.session.username='xyz';
res.send('Filling the session with data');
});
app.get('/bar', function(req, res, next) {
console.log(req.session);
var sessionData = req.session.username;
res.send(`This will print the attribute I set earlier: ${sessionData}`);
});
exports.app = functions.https.onRequest(app);
When I run this, it creates new session in the DB.
And every time I refresh the page, there is a new session.
I want of course, that only one session would be created,
and that on refresh, this session would only be updated, or to get the data from there. not to create a new one every time.
Checking the cookies - showed me that no cookie is saved / created.
I've been working on this for hours...
this was frustrating when I was using firebase functions and hosting, but can be solved by simply setting name:"__session" in the session.
app.use(session({
store: new FirebaseStore({
database: ref.database()
}),
name:"__session
...
I can't find a way how to read in the .get() block the specific session value, that was assigned in the .ws() block recently:
const express = require('express');
const app = express();
const ws = require('express-ws')(app);
const session = require('express-session');
app.use(session({secret: 'secret', resave: true, saveUninitialized: true}));
app.get('/', function(req, res) {
console.log(req.session.val) //undefined (would like to have "my value")
res.end("<script>var ws = new WebSocket(window.location.href.replace('http', 'ws')); ws.send(true);</script>");
})
.ws('/', function(ws, req) {
//trying to assign session
req.session.val = 'my value';
});
app.listen(80);
Please, help.