NodeJS + Express: share session across multiple routes - javascript

I have an Express web application with some routes. The routes need to share the session when the web app interacts with users. The routes are declared in separate js files from the app.js.
In my app.js
var createError = require('http-errors');
var express = require('express');
var parseurl = require('parseurl')
var session = require('express-session')
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var p_conf = require('./parse_config');
// Declare routes here
var indexRouter = require('./routes/index'); // index route
var usersRouter = require('./routes/users'); // user route
var itemRouter = require('./routes/items'); // item route
var app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// set up express-session
var sessionMiddleware = session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true
});
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/items', itemRouter);
// Assign an object to the session
app.use(function (req, res, next) {
req.session.test = "test";
next();
});
module.exports = app;
In my item.js for the item route:
const path = require('path');
const express = require('express');
const fetch = require('node-fetch');
const router = express.Router();
const p_conf = require('../parse_config');
const db_item = require('../db/db_item');
/* GET route root page. */
router.get('/', function(req, res, next) {
// Get the object in the session
console.log(req.session.test);
db_item.getItems()
.then(function(result) {
if (typeof result === "object")
return res.send(result["results"]);
else
return res.send(JSON.stringify({ "Error": String(result) }));
})
.catch((err) => {
return next(err);
})
});
module.exports = router;
In the app.js the session is created and assigned with a test object when the web app is initialised. The item route is supposed to get the same session and retrieve the test object. However, req.session.test is always undefined when the route root is accessed.
How can the item and user routes access the session and share the session scoped objects across?

Try changing the order of declaring routes and session in app.js. Also, need to use sessionMiddlware (app.use) before using session.
var sessionMiddleware = session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true
});
app.use(sessionMiddleware);
app.use(function (req, res, next) {
req.session.test = "test";
next();
});
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/items', itemRouter);

Related

Express JS session value undefined?

let createError = require("http-errors");
let express = require("express");
let path = require("path");
let cookieParser = require("cookie-parser");
let logger = require("morgan");
const session = require("express-session");
let fileStore = require("session-file-store")(session);
const oneDay = 1000 * 60 * 60 * 24;
// Routers
let indexRouter = require("./routes/index");
let usersRouter = require("./routes/users");
let loginPage = require("./routes/login");
let app = express();
// System settings
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
app.set("trust proxy", 1);
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use(
session({
secret: "SECRET_KEY_FOR_SESSION",
saveUninitialized: true,
resave: false,
cookie: { maxAge: oneDay, secure: !true },
store: new fileStore(),
})
);
app.use("/", indexRouter);
app.use("/login", loginPage);
app.use("/users", usersRouter);
app.get("/createSession", (req, res, next) => {
res.send("This is sessionCreate file");
let mysession = req.session.save;
mysession.data = "LOGIN";
res.end;
});
app.get("/getSession", (req, res, next) => {
let getsession = req.session;
res.send(`${getsession.data}`);
res.end;
});
// 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;
getsession.data === undefined?
I uploaded a variable to the session but it was not detected?
All system settings are set correctly but what is the error? Session => The session is being saved to a storage folder but cannot be read.
session_saved_folder
Specifies the boolean value for the Secure Set-Cookie attribute. When truthy, the Secure attribute is set, otherwise it is not. By default, the Secure attribute is not set.
Note be careful when setting this to true, as compliant clients will not send the cookie back to the server in the future if the browser does not have an HTTPS connection.
Please note that secure: true is a recommended option. However, it requires an https-enabled website, i.e., HTTPS is necessary for secure cookies. If secure is set, and you access your site over HTTP, the cookie will not be set. If you have your node.js behind a proxy and are using secure: true, you need to set "trust proxy" in express:

PassportJS nodejs request https

After inserting ssl in my application nodejs the passportjs used for authentication layer informs that the user is not authenticated in the application after an AJAX POST is performed and the page undergoes a window.location.replace().
I have already looked at the documentation and found no reference to the problem, localhost using hpp I do not have this problem.
Would anyone help?
app.js
var express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('morgan');
var path = require('path');
var fileUpload = require('express-fileupload');
var https = require('https');
var fs = require('fs');
var httpsOptions = {
key: fs.readFileSync(path.join("key.pem")),
cert: fs.readFileSync(path.join("cert.pem"))
};
var app = express();
var expressValidator = require('express-validator');
var passport = require('passport');
var flash = require('connect-flash');
// - Cria rotas
var routes = require('./routes/index');
var usuarios = require('./routes/usuario');
var motorista = require('./routes/motorista');
var login = require('./routes/login');
var aluno = require('./routes/aluno');
var contrato = require('./routes/contrato');
var boleto = require('./routes/boleto');
var pessoa = require('./routes/pessoa');
require('./security/autenticacao')(passport);
app.use(logger('dev'));
app.use(expressValidator());
app.use(cookieParser());
app.use(bodyParser.json({limit: "50mb"}));
app.use(bodyParser.urlencoded({limit: "50mb", extended: true, parameterLimit:50000}));
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(session({
secret: 'reis&turlwaysrunning',
resave: true,
saveUninitialized: true
} ));
app.use(logErrors);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(function (req, res, next) {
res.locals.login = req.user;
next();
});
app.use(fileUpload());
// Atriui rotas
app.use('/home', routes);
app.use('/usuarios', usuarios);
app.use('/alunos', aluno);
app.use('/motoristas', motorista);
app.use('/contratos', contrato);
app.use('/login', login);
app.use('/boletos', boleto);
app.use('/pessoas', pessoa);
https.createServer(httpsOptions, app).listen(8080);
app.set('port', process.env.PORT || 21108);
app.listen(app.get('port'));
function logErrors (err, req, res, next) {
console.error('Troxa: ' + err.stack)
next(err)
}
module.exports = app;

NODE.JS Cannot get my data right, any input?

I am new to Node (frameworks in general), and I have some problems that I cannot find answers to after searching for days.
When I click on a specific client, I now get redirected to 'create-survey' which is correct. But after that I want the url to be something like '/create-survey/companyx' and get the data with me from that specific client that I clicked on in the new view '/create-survey/companyx'.
index.js:
router.get('/create-survey/:company', ensureAuthenticated, function(req, res) {
Client.find({}, {}, function (err, docs){
res.render('create-survey/:company', {"client" : docs});
})
});
app.js
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/loginapp');
var db = mongoose.connection;
// Routes
var routes = require('./routes/index');
var users = require('./routes/users');
// Init App
var app = express();
// View Engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout:'layout'}));
app.set('view engine', 'handlebars');
// BodyParser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Passport init
app.use(passport.initialize());
app.use(passport.session());
// Express 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 to Flash
app.use(flash());
// Global Vars
app.use(function (req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});
app.use('/', routes);
app.use('/users', users);
app.use(express.static('public'));
// Set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function(){
console.log('Server started on port '+app.get('port'));
});
and the last, create-survey.handlebars
<h2 class="page-header">Create a survey for {{client.company}}</h2>
<tr>
<strong>Company</strong>
<td><p>{{client.company}}</p></td>
<strong>Contact person</strong>
<td><p>{{client.contact}}</p></td>
<strong>Email adress</strong>
<td><p>{{client.email}}</p></td>
</div>
As I said, I'm a beginner that still is trying to learn, so come with all kind of feedback and help and I'll be happy!

Cannot GET with nodejs?

I have a simple nodejs app with some users. I want to load a specific user profile using a URL localhost/users/(username) but I'm getting this error when I try to load the URL:
Cannot GET /users/test
Here's my user.js routes file for the user page:
var express = require('express');
var router = express.Router();
var User = require('../models/user');
// GET user by username
router.get('/users/:username', function(req, res) {
var username = req.params.username;
res.send(req.params);
res.render('user');
});
module.exports = router;
I have a user.handlebars file in my views folder so it should load the file. What am I missing in my routes file? Any help would be greatly appreciated. Thanks!!
EDIT: app.js:
console.log('Starting app.js');
const fs = require('fs');
const _ = require('lodash');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const mongo = require('mongodb');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/tipcup');
var db = mongoose.connection;
const routes = require('./routes/index');
const users = require('./routes/users');
const user = require('./routes/user');
// Init App
var app = express();
// View Engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout: 'layout'}));
app.set('view engine', 'handlebars');
// BodyParser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
app.use(cookieParser());
// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Passport Init
app.use(passport.initialize());
app.use(passport.session());
// Express 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());
// Global Vars
app.use(function (req, res, next){
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});
app.use('/', routes);
app.use('/users', users);
app.use('/users/:username', user);
// Set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function(){
console.log('Server started on port '+app.get('port'));
});
Render function renders a view and sends the rendered HTML string to the client.Take a look at documentation.
But what you are trying to archive is to send data first and then render and send again. So, just delete the line with send.
router.get('/users/:username', function(req, res) {
var username = req.params.username;
res.render('user');
});
And, please, edit your question by adding your code with middleware and add your error.
Update
Take a look at the way how you define your routes for users.
You have to remove /users from defining route in users.js file

Node.js not rendering in index.handlebars?

Ive been recently learning how to use node.js to create a backend login system with passport. Im running it locally with a mongoDB. The url I use to access it is http://localhost:3000. Now when I go to that url instead of displaying my index.handlebars page it routes me to http://localhost:3000/users/login. Im wondering why this is? Ill provide a few files let me know if there is anything else you may need.
Not sure what else you would need, but I have looked through my code hundreds of times and cant find out why. My routes seem fine, my static folder seems fine. Im just lost. Any help would be appreciated.
My directory looks like this,
loginapp-master
-models
-users.js
-node_modules
-public
-css
-fonts
-js
-routes
-index.js
-users.js
-views
-layouts
-layout.handlebars
-index.handlebars
-login.handlebars
-register.handlebars
.gitignore
app.js
package-lock.json
package.json
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/loginapp');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
// Init App
var app = express();
// View Engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout:'layout'}));
app.set('view engine', 'handlebars');
// BodyParser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Passport init
app.use(passport.initialize());
app.use(passport.session());
// Express 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());
// Global Vars
app.use(function (req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});
app.use('/', routes);
app.use('/users', users);
// Set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function(){
console.log('Server started on port '+app.get('port'));
});

Categories