I'm working currently with one NodeJS + Express + Mongodb Applicacion and I need to get information stored in another monogodb database. So in my app.js file I'm doing the following steps in my app:
app.js
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var mongoose = require('mongoose');
var passport = require('passport');
var configDB = require('./config/database.js');
// here I get the info from the Database IP and port.
mongoose.connect(configDB.url);
app.use( session({store: new MongoStore({mongoose_connection: mongoose.connections[0]}),
secret: 'secretPass',
cookie: {maxAge: 36000}, // session secret
saveUninitialized: true,
resave: true}
));
Is there a way to add another connection so I can use it so get information stored in the second database?
Thanks a Lot!
You can use the following code:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/database1'); // database connection
mongoose.connect('mongodb://localhost/database2');
Related
The code from here works for the basic case when urls are known in advance.
How to handle dynamic protection of urls by Keycloak after middleware was added and express app started?
I was thinking about handling reading new urls from file by some node.js module which will emit the event and then the code below would handle the event. In the code of event handler, the call to app.all('/new url', keycloak.protect()) will be added.
I tried that but it doesn't work as expected because of the app.use('/lap', [some_midleware]) is before the new app.all('/new url', keycloak.protect()
The only way i think of is modifying app._router.stack by inserting the new middleware before the some_midleware
var Keycloak = require('keycloak-connect');
var hogan = require('hogan-express');
var express = require('express');
var session = require('express-session');
var fs = require()
var app = express();
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);
});
var memoryStore = new session.MemoryStore();
app.use(session({
secret: 'mySecret',
resave: false,
saveUninitialized: true,
store: memoryStore
}));
var keycloak = new Keycloak({
store: memoryStore
});
app.use(keycloak.middleware({
logout: '/logout',
admin: '/',
protected: '/protected/resource'
}));
app.all('/url', keycloak.protect())
app.all('*', [some_midleware])
From what I understand, you want to dynamically add new routes that get handled before the last route in your example (app.use('*', ...)).
You could do that with a separate router:
app.all('/url', keycloak.protect())
const router = express.Router();
app.use(router);
app.use('*', [some_midleware])
Then, to add new route handlers, you'd add them to router, not app:
router.get('/new url', keycloak.protect());
Because router is added before app.use('*', ...), it will always get to handle requests first. Only if requests don't match any handlers will be pass the request on the handler on the last line.
I've been having problems trying to access stored session values! Once I've set the values and try access them from a new route, I get undefined! So basically I've got a login (POST) and in that request I set the session data, and then I have a show user details (POST) where I try and access the session data I've just stored.
Setup
// Setup express and needed modules #############################################
var express = require('express'),
session = require('express-session'),
cookieParser = require('cookie-parser'),
redis = require("redis"),
redisStore = require('connect-redis')(session),
bodyParser = require('body-parser');
var client = redis.createClient(), //CREATE REDIS CLIENT
app = express();
// Setup app
app.use(cookieParser('yoursecretcode'));
app.use(session(
{
secret: 'x',
store: new redisStore({
port: 6379,
client: client
}),
saveUninitialized: true, // don't create session until something stored,
resave: false // don't save session if unmodified
}
));
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
app.set('trust proxy', 1) // trust first proxy
So as you've seen my setup, you know I'm using express sessions and Redis. Below is where I'm setting the session values! If I print out the session values here it works, but then If I try and access the session data in another route it returns undefined.
Routes
I send a http post request and set the session data:
router.route('/login/').post(function(req, res) {
req.session.userId = req.body.uId;
req.session.name = req.body.uName;
// THIS PRINTS OUT IF I TRY AND ACCESS THE SESSION DATA HERE
console.log("THIS PRINTS OUT --> " + req.session.name);
});
So now that the session values have been set, I can go access them right, no, I get undefined each time I try and log them out.
router.route('/user/printoutuserdetails').post(function(req, res) {
// THESE RETURN UNDEFINED
console.log(req.session.userId);
console.log(req.session.uName);
console.log("THIS PRINTS OUT --> " + req.session.name);
});
Does anyone have any idea what's happening? I've tried everything and looked everywhere and can't seem to find a way to get it to work!
Solved:
The reason this wasn't was because you're not suppose to use sessions when using a RESTFUL api.
I'm new to NodeJS. I am developing a REST API and using express-session to deal with sessions. So, to get the session ID I'm using
var sessionID = req.sessionID
This sessionID is generated from the server side. So, when I scale up to two or more servers, this is a problem. For example, if one server shuts down and the request is redirected to another server (Assuming I have a load balancer), a new session ID is generated. So, is there a way to retrieve the session ID from the client side?
Good question! Session management can be challenging to get up and running with - especially since to get up and running with any sort of sophisticated session management in node you need a ton of different packages, each with their own set of docs. Here is an example of how you can set up session management with MongoDB:
'use strict';
var express = require('express'),
session = require('express-session'),
cookieParser = require('cookie-parser'),
mongoStore = require('connect-mongo')(session),
mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/someDB');
var app = express();
var secret = 'shhh';
app.use(session({
resave: true,
saveUninitialized: true,
secret: secret,
store: new mongoStore({
mongooseConnection: mongoose.connection,
collection: 'sessions' // default
})
}));
// ROUTES, ETC.
var port = 3000;
app.listen(port, function() {
console.log('listening on port ' + port + '.')
});
This configuration gives you access to req.sessionID but now it should persists across app servers if the user's session cookie has not expired.
I hope this works!
I have a simple, generic express app. It logs the req.sessionID whenever a certain route is hit. I would expect that refreshing the client page would result in the same sessionID being logged again. This works, if I've imported passport and added the passport middleware after the session middleware. If I either don't use passport at all, or I add passport middleware before the session middleware, then the sessionID is different every time.
I can accept that the ordering of middleware can be finicky. However, my app doesn't use passport at all, so I can't fathom why my app doesn't work if I don't require passport. Should passport be necessary for sessions to work?
//generic express initialization
var http = require('http');
var express = require('express');
var cookieParser = require('cookie-parser');
var passport = require('passport');
var session = require('express-session');
var app = express();
var server = http.createServer(app);
var sessionMiddleware = session({resave: false, saveUninitialized: false, secret: 'hunter2'});
app.use(cookieParser());
//This works:
app.use(sessionMiddleware);
app.use(passport.initialize());
//This doesn't:
app.use(passport.initialize());
app.use(sessionMiddleware);
Switch to resave: true, saveUninitialized: true
Unmodified sessions were not being saved, thus resulting in repeatedly generating new session IDs. Passport, however, was presumably doing some initialization on the session, meaning that the session was no longer unmodified.
Thanks to #Dodekeract and #Swaraj Giri for figuring the issue in their comments!
i am trying to create session with mongodb in node.js
already i have a connection like this
var Db=require('mongodb').Db;
var BSON=require('mongodb').BSONPure;
var Server=require('mongodb').Server;
var client=new Db('db',new Server('localhost', 27017), {safe:false});
and then i have tried to configure session like this
app.use(express.session({
store: new mongoStore({ db: client }),
secret: 'topsecret'
}));
i ran the server.js file i got this error mongoStore undefined
so to resolve this error i have added this
var mongoStore= require('connect-mongodb');
again i ran it i did't get any error but i got below error when i tried to find or save data into db
Cannot call method 'findOne' of undefined
how to resolve this problem and how to create session with mongodb in node.js
Here's a very simple setup:
var express = require('express');
var MongoStore = require('connect-mongo')(express);
var app = express();
app.use(express.cookieParser()); // required to handle session cookies!
app.use(express.session({
secret : 'YOUR_SESSION_SECRET',
cookie : {
maxAge : 10000 // expire the session(-cookie) after 10 seconds
},
store : new MongoStore({
db: 'sessionstore'
// see https://github.com/kcbanner/connect-mongo#options for more options
})
}));
app.get('/', function(req, res) {
var previous = req.session.value || 0;
req.session.value = previous + 1;
res.send('<h1>Previous value: ' + previous + '</h1>');
});
app.listen(3012);
If you run it and open http://localhost:3012/ in your browser, it will increase the value by 1 each time you reload. After 10 seconds, the session will expire and the value will be reset to 0.