Express js req.session always undefined - node.js

I used Express Node.js to make login page with SQL server and I want to use session. Here's my code:
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var admin = require('./routes/admin');
var http = require('http');
var path = require('path');
var bodyParser = require('body-parser');
var session = require('express-session');
var async = require("async");
var edge = require('edge');
var cookieParser = require('cookie-parser');
var app = express();
// all environments
app.set('port', process.env.PORT || 3030);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'assets')));
app.use(express.cookieParser());
app.use(express.session({
cookieName: 'session',
secret: 'dgjdjdfjfjhhytjhd',
duration: 30 * 60 * 1000,
sctiveDuration: 50 * 60 * 1000,
cookie: { maxAge: 24 * 60 * 60 * 1000 }
}));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
///////////// Routs Here .......
app.get('/', function(req, res) {
res.send('<h5>Welcome</h5>Go To Login');
});
app.get('/login', function(req, res) {
res.render('login');
});
/*======================================= Post For Login & Redirect To Admin Page =====================================*/
app.post('/login', function (req, res) {
var username = req.body.username;
var password = req.body.password;
var params = {
connectionString: "Data Source=AHMAD-HOME;Initial Catalog=nodejs;Integrated Security=True",
source: "SELECT * FROM users WHERE username='"+ username+"' and password='"+ password+"'"
};
var getUsers = edge.func('sql', params);
getUsers(null, function (error, result) {
if (error) throw error;
if (result) {
if (result == '') {
console.log(' Empty Data From Database');
res.redirect('/login');
} else {
req.session.userid= result;
res.redirect('admin');
}
} else {
console.log('kkkkkkkkkkk');
}
});
console.log('The UserName Is ' + username + ' And The Password Is : ' + password);
});
app.get('/admin', function (req, res) {
res.render('admin');
console.log(req.session);// stack here
});
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
I always have an undefined session on admin page.
I used express-session and I tried client-session before but I still the same error.

app.use(**express.**session({
cookieName: 'session',
secret: 'dgjdjdfjfjhhytjhd',
duration: 30 * 60 * 1000,
sctiveDuration: 50 * 60 * 1000,
cookie: { maxAge: 24 * 60 * 60 * 1000 }
}));
Remove the part in **s. That has been deprecated in the newest releases of Express. You have to use the middleware express-session, which you have already set up and assigned to session.

Related

how to access express-myconnection db connection from app.js to model node js

I have defined express-myconnection database connection in app.js now i want to use that database connection in models like tasks.js how do I implement that connection in models also.Please suggest me better option.
app.js
var createError = require('http-errors');
var express = require('express');
var session = require('express-session');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
// var passport = require('passport');
var cors=require('cors');
var flash = require('connect-flash');
var mysql = require('mysql');
// require('./config/passport')(passport);
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var Tasks=require('./routes/Tasks');
var app = express();
var customers = require('./routes/customers');
var login = require('./routes/login');
var connection = require('express-myconnection');
// view engine setup
// app.set('port', process.env.PORT || 4300);
app.engine('pug', require('pug').__express);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// app.use(passport.initialize());
app.use(session({
secret: 'justasecret',
resave:true,
cookie: {
httpOnly: true,
maxAge : 10000,
},
saveUninitialized: true
}));
/*------------------------------------------
connection peer, register as middleware
type koneksi : single,pool and request
-------------------------------------------*/
// app.use(
// connection(mysql,{
// host: 'localhost',
// user: 'root',
// password : '',
// port : 3306, //port mysql
// database:'nodejs'
// },'pool')
// );//route index, hello world
dbOptions = {
host: 'localhost',
user: 'root',
password: '',
port: 3307,
database: 'nodejs'
};
// const db = mysql.createPool(dbOptions);
app.use(connection(mysql, dbOptions, 'pool'));
app.use(cors());
app.use(logger('dev'));
// app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(flash());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/customers', customers);
app.use('/admin',login);
app.use('/tasks',Tasks);
// require('./routes/login.js')(app, passport);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
inside models/tasks.js=>
var Task={
getAllTasks:function(callback){
return db.query("Select * from task",callback);
},
getTaskById:function(id,callback){
return db.query("select * from task where Id=?",[id],callback);
},
addTask:function(Task,callback){
return db.query("Insert into task values(?,?,?)",[Task.Id,Task.Title,Task.Status],callback);
},
deleteTask:function(id,callback){
return db.query("delete from task where Id=?",[id],callback);
},
updateTask:function(id,Task,callback){
return db.query("update task set Title=?,Status=? where Id=?",[Task.Title,Task.Status,id],callback);
}
};
module.exports=Task;
express-myconnection extends request object with getConection(callback) function, this way connection instance can be accessed anywhere in routers during request/response life cycle:
// myroute.js
...
module.exports = function(req, res, next) {
...
req.getConnection(function(err, connection) {
if (err) return next(err);
connection.query('SELECT 1 AS RESULT', [], function(err, results) {
if (err) return next(err);
results[0].RESULT;
// -> 1
res.send(200);
});
});
...
}
...

MongoError - caused by npm module connect-mongo

Im getting these errors
MongoError: server instance pool was destroyed
MongoError: Topology was destroyed
i'd love if anyone would know what is causing this module to make these errors and how to fix it.
.
MongoError: server instance pool was destroyed
at basicWriteValidations (/home/jnyheim/var/www/node_modules/mongodb-core/lib/topologies/server.js:698:41)
at Server.update (/home/jnyheim/var/www/node_modules/mongodb-core/lib/topologies/server.js:834:16)
at Server.update (/home/jnyheim/var/www/node_modules/mongodb/lib/topologies/topology_base.js:326:25)
at updateDocuments (/home/jnyheim/var/www/node_modules/mongodb/lib/operations/collection_ops.js:1344:19)
at /home/jnyheim/var/www/node_modules/mongodb/lib/utils.js:437:24
at new Promise ()
at executeOperation (/home/jnyheim/var/www/node_modules/mongodb/lib/utils.js:432:10)
at Collection.update (/home/jnyheim/var/www/node_modules/mongodb/lib/collection.js:829:10)
at withCallback.collectionReady.then.collection (/home/jnyheim/var/www/node_modules/connect-mongo/src/index.js:244:48)
at
at process._tickCallback (internal/process/next_tick.js:188:7)
MongoError: Topology was destroyed
at nextFunction (/home/jnyheim/var/www/node_modules/mongodb-core/lib/cursor.js:603:27)
at Cursor.next (/home/jnyheim/var/www/node_modules/mongodb-core/lib/cursor.js:824:3)
at Cursor._next (/home/jnyheim/var/www/node_modules/mongodb/lib/cursor.js:211:36)
at nextObject (/home/jnyheim/var/www/node_modules/mongodb/lib/operations/cursor_ops.js:186:10)
at next (/home/jnyheim/var/www/node_modules/mongodb/lib/operations/cursor_ops.js:165:3)
at executeOperation (/home/jnyheim/var/www/node_modules/mongodb/lib/utils.js:420:24)
at Cursor.next (/home/jnyheim/var/www/node_modules/mongodb/lib/cursor.js:253:10)
at findOne (/home/jnyheim/var/www/node_modules/mongodb/lib/operations/collection_ops.js:542:10)
at /home/jnyheim/var/www/node_modules/mongodb/lib/utils.js:437:24
at new Promise ()
at executeOperation (/home/jnyheim/var/www/node_modules/mongodb/lib/utils.js:432:10)
at Collection.findOne (/home/jnyheim/var/www/node_modules/mongodb/lib/collection.js:1021:10)
at withCallback.collectionReady.then.collection (/home/jnyheim/var/www/node_modules/connect-mongo/src/index.js:192:46)
at
I found that its caused by this
const MongoStore = require('connect-mongo')(session);
module while executing
store: new MongoStore({mongooseConnection: mongoose.connection})
app.use(session({
secret: "mylittle34secret",
cookie: { maxAge: (1 * 60 * 60 * 1000) },
saveUninitialized: false,
resave: false,
proxy: true,
store: new MongoStore({mongooseConnection: mongoose.connection}),
}));
full code:
'use strict'
// Dependencies
const expressValidator = require('express-validator');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const passport = require('passport');
const mongoose = require('mongoose');
const express = require('express');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const exphbs = require('express-handlebars');
const paypal = require('paypal-rest-sdk');
const flash = require('connect-flash');
const path = require('path');
mongoose.connect('mongodb://localhost:27017/app', {useNewUrlParser: true, socketTimeoutMS: 0, keepAlive: true, reconnectTries: 30}, (err, db)=>{
if(err){
console.log('## INCOMMING MONGO ERROR ##' + err + '## MONGO ERROR END ##');
throw err;
}else{
console.log("--> succesfully connected to Database!");
};
//db.once('')
});
const paypal_config = require('./lib/helpers/paypal_configuration.json');
paypal.configure(paypal_config);
const app = express()
// Root Routes
const _shop = require('./route/shop');
const _index = require('./route/index');
const _about = require('./route/about');
const _session = require('./route/session');
const _projects = require('./route/projects');
// View Engine
app.engine('.hbs', exphbs({
extname: '.hbs',
defaultLayout:'layout',
layoutsDir: __dirname + '/views/layouts/'
}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
// BodyParser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// Set Static Folder | Public Folder
app.use(express.static(path.join(__dirname, 'public')));
// Express Session
app.use(session({
secret: "mylittle34secret",
cookie: { maxAge: (1 * 60 * 60 * 1000) },
saveUninitialized: false,
resave: false,
proxy: true,
store: new MongoStore({mongooseConnection: mongoose.connection}),
}));
// Passport init
app.use(passport.initialize());
app.use(passport.session());
// Express Body Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
// Connect Flash
app.use(flash());
// Vars for HTML doc
app.use((req, res, next)=>{
res.locals.success_msg = req.flash('success_msg');
res.locals.warning_msg = req.flash('warning_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.info_msg = req.flash('info_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
res.locals.session = req.session;
next();
});
// root/routes
app.use('/', _index); // x/
app.use('/shop', _shop); // x/shop
app.use('/about', _about); // x/about
app.use('/session', _session); // x/session
app.use('/projects', _projects); // x/projects
// Server
app.set('port', (process.env.PORT || 80));
app.listen(app.get('port'), ()=>{
console.log('--> HTTP Server started on port %s', app.get('port'));
});
<3

Express.js session undefined. Redis

Trying to get sessions set up with Redis. I have my Redis DB in a dokku container, linked to my app (also in a dokku container). I keep getting a session undefined.I've stripped things back to the bare minimum, also checked the order in which things are run. I still get an undefined.
I've read here 'session' is undefined when using express / redis for session store and Express js session undefined to no avail.
I shouldn't need to use cookie-parser, as expression-session has cookie stuff in it, and the docs say cookie-parser can cause problems with expression-session.
var express = require('express');
var session = require('express-session');
var redisStore = require('connect-redis')(session);
var bodyParser = require('body-parser');
var app = express();
app.set('port', (process.env.PORT || 5000));
var redisURL = 'redis://xxxxx:1234567#bar-redis-foo:6379';
var store = new redisStore({ url: redisURL });
app.use(session({
secret: 'ssshhhhh',
store: store,
saveUninitialized: true,
resave: true
}));
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.get('/', function(req, res, next) {
console.log(req.session); // Logs Undefined
res.send('Hello');
});
Check your redis connection and run again. Sample code is following line.
"use strict";
const express = require("express");
const bodyParser = require("body-parser");
const session = require("express-session");
const RedisStore = require("connect-redis")(session);
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(session({
secret: "$kx(Fj$uB!Ug!#jCkguFmc6f7t<c-e$9",
resave: false,
saveUninitialized: true,
store: new RedisStore({
url: "redis://:********#pub-redis-12766.eu-central-1-1.1.ec2.redislabs.com:12766",
ttl: 5 * 60 // 5 minute (Session store time)
})
}));
app.use(function (request, response, next) {
let path = request.originalUrl;
if (request.session.user) {
request.session.reload(function (err) { //session expire time regenerate
if (!err) {
next();
} else {
response.redirect('/login');
}
});
} else {
if (path == '/login') {
next();
} else {
response.redirect('/login');
}
}
});
app.get('/', function(request, response) {
if (request.session.user) {
response.send(request.session.user);
} else {
response.redirect("/login");
}
});
app.get('/login', function(request, response) {
if (request.session.user) {
response.redirect("/");
} else {
request.session.user = {username: "halil"}; //custom key {user} and custom data {username: "halil"}
}
response.send('Login');
});
app.get('/logout', function(request, response) {
if (request.session.user) {
request.session.destroy();
response.redirect("/login");
} else {
response.redirect("/login");
}
});
app.listen(app.get('port'), function () {
console.log('App is working on port: ' + app.get('port'));
});

Supertest returns no result and node instances don't exit

I'm just learning testing and I've been at it for a few hours no with no success. Every time I run Mocha, my test shows up in the terminal and returns no result, like this:
Express test app started on port: 3001
addition
It stays blank afterwards. Further, the node processes don't close after testing and when they stack up they crash my computer.
Here is my sample test:
var supertest = require('supertest');
var should = require('should');
process.env.NODE_ENV = 'test';
var app = require('../server');
describe('addition', function() {
//... previous test
it('should return 2 given the url /add/1/1', function(done) {
request(app)
.get('/add/1/1')
.expect(200)
.end(function(err, res) {
should.not.exist(err);
parseFloat(res.text).should.equal(2);
done();
});
});
});
Here is my server.js
// Module Depndencies
var express = require('express'),
fs = require('fs'),
mongoose = require('mongoose'),
passport = require('passport'),
MongoStore = require('connect-mongo')(express),
flash = require('connect-flash'),
env = process.env.NODE_ENV = process.env.NODE_ENV || 'development',
ErrorHandler = require('./app/controllers/api/v1/error_handler_v1'),
config = require('./config/config'),
auth = require('./config/middlewares/authorization');
// Connect The Database
mongoose.connect(config.db);
// Catch Database Connection Error
mongoose.connection.on("error", function(err) {
return console.log("****** Could not connect to mongo server!");
});
// Express Settings
app = express();
app.set('showStackError', true);
//Should be placed before express.static
app.use(express.compress({
filter: function(req, res) {
return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
},
level: 9
}));
//Setting the fav icon and static folder - tejkh
app.use(express.favicon());
app.use(express.static(config.root + '/public'));
//Don't use logger for test env
if (process.env.NODE_ENV !== 'test') app.use(express.logger('dev'));
//Set views path, template engine and default layout
app.set('views', config.root + '/app/views');
app.set('view engine', 'jade');
// Enable jsonp
app.enable('jsonp callback');
//Bootstrap models
var models_path = __dirname + '/app/models';
var walk = function(path) {
fs.readdirSync(path).forEach(function(file) {
var newPath = path + '/' + file;
var stat = fs.statSync(newPath);
if (stat.isFile()) {
if (/(.*)\.(js|coffee)/.test(file)) {
require(newPath);
}
} else if (stat.isDirectory()) {
walk(newPath);
}
});
};
walk(models_path);
// Bootstrap Passport
require('./config/passport')(passport);
// App.configure
app.configure(function() {
// CookieParser should be above session
app.use(express.cookieParser());
// BodyParser should be above methodOverride
app.use(express.bodyParser());
app.use(express.methodOverride());
// Express/mongo session storage
app.use(express.session({
secret: 'secret',
cookie: {
maxAge: 864000000 // 10 Days in miliseconds
},
store: new MongoStore({
url: config.db,
auto_reconnect: true
})
}));
// Connect flash for flash messages
app.use(flash());
// Use Passport
app.use(passport.initialize());
app.use(passport.session());
// Route
app.use(app.router);
// Error Handler
app.use(function(err, req, res, next) {
if (err.uri) delete err.uri;
if (err.status) {
return res.status(err.status).jsonp(err);
} else {
res.status(500).jsonp({
name: 'InternalError',
message: 'Sorry, something went wrong on our end. We have been notified.',
code: 'server_error',
status: 500
});
}
});
}); // app.configure
//Bootstrap routes
require('./config/routes')(app, passport, auth);
// Start App
app.listen(config.port);
console.log('Express ' + env + ' app started on port: ' + config.port);
// Expose app
exports = module.exports = app;
If you use:
var supertest = require('supertest');
then you should use:
supertest(app)
and not:
request(app)
try this, maybe it will work
request('http://host:port')

Express: unable to access POST data and set cookie at the same time

I'm writing an application that takes in a post request and sets a cookie pulled from the POST info. I'm stuck in a catch 22. In the first code sample I can set the cookie but can't access the data, in the second I can access the data but can't set the cookie. I'm sure I'm missing some basic concept of how the middle ware works but I can't for the life of me find the info I need.
The code below creates the cookie as expected but my post variable become undefined
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, handshake = require('./routes/handshake')
, http = require('http')
, path = require('path');
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(function (req, res, next) {
var cookie = req.cookies.cokkieName;
console.log("cookie_name" , cookie);
if (cookie === undefined)
{
//cookie is set but I can't use req.post.xxxx. It"s always undefined
res.cookie("price", 111, { maxAge: 10000 });
console.log('cookie has been created successfully');
}
else
{
console.log('cookie exists', cookie);
}
next();
});
app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
app.post('/handshake', handshake.token);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
The following code executes the setCookie callback (because the console output shows up), and on the console the variables are properly defined, but the cookie is not set.
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, handshake = require('./routes/handshake')
, http = require('http')
, path = require('path');
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
var setCookie = function (req, res, next) {
var cookie = req.cookies.cokkieName;
console.log("cookie_name" , cookie);
if (cookie === undefined)
{
res.cookie("price", 111, { maxAge: 10000 });
//in the console the post.body.xxxx data appears correctly but no cookie!!!
console.log('cookie has been created successfully',post.body.xxx);
}
else
{
console.log('cookie exists', cookie);
}
next();
};
app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
app.post('/handshake', setCookie ,handshake.token);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Trying to make the code more readable introduced too many typos that weren't relevant to my code. I took the suggestion and changed the code in the following way but it still doesn't write a cookie to the client.
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, handshake = require('./routes/handshake')
, http = require('http')
, crypt = require('crypto')
, io = require('socket.io')
, db = require('levelup')('./mydb')
, path = require('path');
var app = express();
app.use(express.cookieParser());
app.use(express.bodyParser());
var cookieMiddleware = function (req, res, next) {
var cookie = req.cookies.user;
console.log("cookie_name" , cookie);
if (cookie === undefined)
{
// no: set a new cookie
var random = Math.random().toString();
random=random.substring(2,random.length);
sessionToken = Date.now() + random;
salt = sessionToken + req.body.address;
sha2 = crypt.createHash('sha256');
sha2.update(sessionToken);
var price = req.body.price;
var encryptedSession = sha2.digest('hex');
console.log('post body',price );
res.cookie('user','price' , { maxAge: 100000 });
console.log('existing cookies', req.cookies);
}
else
{
console.log('cookie exists', req.cookies);
}
next();
};
//development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.session({secret: "TheSuperSecretStringForHashing"}));
app.use(express.methodOverride());
app.use(app.router);
//app.use(express.favicon());
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
app.post('/handshake', cookieMiddleware , handshake.token);
app.get('/', routes.index);
app.get('/users', user.list);
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
io = io.listen(server);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
The handshake.js handler
exports.token = function(req, res){
req.body.title = 'Payment Portal';
res.render('payment_init', req.body);
};
You are checking for a cookie named cokkieName, but the cookie you are setting has the name price.
Try changing this to:
var cookie = req.cookies.price;
cookie should now contain your cookie value.

Resources