Can't seem to figure out how to use redis store for sessions with Express 4, some sample code looks like:
var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
app.use(cookieParser());
app.use(session({
store: new RedisStore({
host: 'localhost',
port: 6379,
}),
secret: 'secret',
resave: false,
saveUninitialized: true
}));
app.get('/', function (req, res) {
console.log(req.session); // undefined! :(
});
app.listen(3000);
As you can see the req.session above always seems to be undefined, and obviously unable to store any variables in there...
Of course, the most frustrating problems have the simplest answers... Redis client was never installed. Link for anyone in the future - http://redis.io/topics/quickstart :facepalm:
looks like you forgot to start redis. try typingservice redis-server start on your server cli. hope it'll help :)
Related
I'm trying to run my node server.js there but it's not working.
I have sent all my files over the FTP in a folder called api (wwwroot is my website, so i need to run this server inside api folder).
Do i need to do something else or what?
Here's my server.js code:
//Dependecies
var express = require('express');
var app = express();
var port = process.env.PORT || 3030;
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var session = require('express-session')
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var passport = require('passport');
var flash = require('connect-flash');
var MongoStore = require('connect-mongo')(session);
var cors = require('./cors');
//Database Configurations
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
//Passport Strategies
require('./config/passport')(passport);
//Morgan Logger
app.use(morgan('dev'));
//Cookie Parser
app.use(cookieParser());
//bodyParser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//Session
app.use(session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true,
cookie: { maxAge: null, secure: false },
store: new MongoStore({
url: configDB.url,
collection: 'sessions'
})
}));
//Connect Flash
app.use(flash());
//CORS Setup
app.use(cors());
//Passport
app.use(passport.initialize());
app.use(passport.session());
//Require the Routes
require('./app/routes.js')(app, passport);
//Start Server
app.listen(port);
console.log('Server is Running!');
EDIT :
When i type in the console, it stops for a bit and print "Bad Request".
Commonly, the 400 BAD request HTTP error code means that the request could not be understood by the server due to malformed syntax. You could check your request url, or post body.
Additionally, you can use the FTP tool to check whether there is a web.config file in your root directory on Azure Web Apps environment. If not, you can manually create one, you can refer to https://tomasz.janczuk.org/2011/08/hosting-express-nodejs-applications-in.html for a sample for an express based application.
Meanwhile, you can refer to https://learn.microsoft.com/en-us/azure/app-service-web/app-service-web-nodejs-best-practices-and-troubleshoot-guide for more info about troubleshooting on node.js applications on Azure Web Apps.
Any further concern, please feel free to let me know.
I am facing an issue with handling session using latest version of Express, Node.js.
My requirement is to store users email id in /login route, and need to get that email id thought out
all routes like /home. But email id is not printing in /home route with my current code. Your help is much appreciate.
My demo code is here
var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
app.set('port',process.env.PORT || 3000);
app.use(cookieParser());
app.use(session({
resave: false,
saveUninitialized: false,
store: new RedisStore({
host: 'localhost',
port: 6379
}),
secret: 'some string/hash secret'
}));
var counter=0;
app.get('/login', function(request, response){
//adding some value to request.session
request.session.email = 'jak#amt.in';
console.log('sessionID', request.sessionID)
response.send('email: '+request.session.email);
});
app.get('/home', function (request, response) {
console.log('home login', request.session.email); // Email not priting here
console.log('sessionID - home', request.sessionID); // Session ID is showing
response.send('home');
});
if (!module.parent) {
console.info('Listening ', process.env.PORT || 5000);
app.listen(process.env.PORT || 5000);
}
module.exports = app;
I am getting following error
"ReplyError: ERR wrong number of arguments for 'set' command
at parseError (/home/dibeesh/obpnode6/testproject/node_modules/redis/node_modules/redis-parser/lib/parser.js:161:12)
at parseType (/home/dibeesh/obpnode6/testproject/node_modules/redis/node_modules/redis-parser/lib/parser.js:222:14)"
Make sure your redis server is running when you run your app.
The code below is quite a normally snippet, but it's not working, session from request is undefined. Anyone who can give me a hint will be appreciated.
var express = require('express');
var session = require('express-session');
var redisStore = require('connect-redis')(session);
var app = express();
app.listen(3000);
app.use(session({
store: new redisStore({
host:'localhost',
port:'8543'
}),
resave: false,
saveUninitialized: true,
secret: 'somesecrettoken'
}));
app.get('/', function (req, res) {
if(req.session.isVisit) {
req.session.isVisit++;
res.send('<p>times to be here:' + req.session.isVisit + '</p>');
} else {
req.session.isVisit = 1;
res.send('1st time to be here');
}
});
A Redis client is required
var redis = require("redis"); // You can use any module to create redis client
app.use(session({
store: new redisStore({
client : redis.createClient(<your setting>)
host:'localhost',
port:'8543'
}),
resave: false,
saveUninitialized: true,
secret: 'somesecrettoken'
}));
Please refer this link:
https://www.npmjs.com/package/connect-redis
Pass the express-session store into connect-redis to create a RedisStore constructor.
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
app.use(session({
store: new RedisStore(options),
secret: 'keyboard cat'
}));
I am using npm subdomain, inside my app I have routes that fake a subdomain
// looks like app.localhost:3000
router.get('/subdomain/app', app.dashboard);
So I have a login page on a subdomain and a login page on a non subdomain page. They don't share sessions, so I have to login twice. I want to setup redis, but I don't know how.
// here is my session middleware, I tried using .localhost
app.use(session({ secret: 'something', domain: '.localhost', }));
I have seen where people are using redis like
app.use(express.session({
store:new RedisStore({
host: config.redis.session.host,
port: config.redis.session.port,
db: config.redis.session.db
}),
secret: config.session_secret
}));
This seems like it could solve my issue but I have no clue how to setup a redisStore and where the config data comes from?
Can someone explain to me how to use redis so that when a user logs in on either app.example.io or example.io that he/she is logged in for good, no need to log in twice?
You need to require following modules.
connect-redis
express-session
cookie-parser
Then use the following sample code:
var express = require('express');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var app = express();
app.use(cookieParser());
app.use(session({
secret: "thisismysecretkey",
store: new RedisStore({ host: 'localhost', port: 6379})
}));
app.get('/', function (req, res) {
res.send('Hello World!')
})
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('Example app listening at http://%s:%s', host, port)
})
Source : How to save and retrieve session from Redis
Here is how I did it, this is the most important piece - domain: .yourdomain.io Make sure to have that preceeding dot before your domain.
var express = require('express'),
app = express(),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
expressSession = require('express-session'),
sessionMiddleware = null,
redis = require('redis'),
conn_redis = {
path: '/var/run/redis/redis.sock',
socket_keepalive: true
}
app.use(cookieParser())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))
const connectRedis = require('connect-redis')(expressSession),
uid = require('uid-safe').sync
sessionMiddleware = expressSession({
store: new connectRedis(conn_redis),
secret: 'xxxxxxxxxxxxxxxxxxxxx',
name: 'session_name',
resave: false,
rolling: true,
saveUninitialized: false,
logErrors: true,
cookie: {
path: '/',
domain: '.yourdomain.io'
expires: new Date(Date.now() + 3600000),
maxAge: 3600000
}
})
First of all i'm rookie with nodejs, i started to learn it about 3-4 days and i read lots of articles but they made me more confuse!
var app = express();
var expressSession = require('express-session');
var cookieParser = require('cookie-parser');
app.use(cookieParser());
app.use(expressSession({
key : 'session',
secret: 'mySecretKey',
store: sessionStore
}));
app.use(passport.initialize());
app.use(passport.session());
var server= require('http').Server(app) ;
var io = require('socket.io')(server);
var passportSocketIo = require("passport.socketio");
io.use(passportSocketIo.authorize({
cookieParser: cookieParser,
key: 'session',
secret: 'mySecretKey',
store: sessionStore,
success: onAuthorizeSuccess,
fail: onAuthorizeFail,
}));
It works great and check socket connection access, but there's a little big problem for me.
How i can access the session id on socket messages?
i want to search session data in my session store and find the current users information.
this piece of code seems not working:
io.on('connection',function(socket) {
socket.on('myevent',function(){
console.log("Session: ", socket.session);
});
});
I found
socket.request.user
It changed in new version.