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
Related
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);
});
});
...
}
...
I have a little probleme with my Nodejs application. I want protect my forms with csrf token, but it's not work. I have an error like
ForbiddenError: invalid csrf token
POST http://localhost:3000/addfile 403 (Forbidden)
I want to create csrf token for all requests. I can create csrf token, but if I use the methods like : POST/PUT or DELETE it's not work.
I don't understand why I have this error. Thanks for yours answers.
app.js
var express = require("express");
var bodyParser = require("body-parser");
var mongoose = require('mongoose');
var fs = require('fs');
var path = require('path');
var logger = require('morgan');
var expressValidator = require('express-validator');
var csrf = require('csurf');
var session = require('express-session');
var passport = require('passport');
var PORT = 3000;
var config = require('./config/database');
var app = express();
// Connexion to MongoDb
mongoose.connect(config.database, function(err) {
if(err){
console.log(err);
}
else{
console.log("Connected to MongoDb");
}
});
// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(expressValidator());
app.set('views',path.join(__dirname, ''));
app.set('view engine','pug');
app.use(express.static(path.join(__dirname, '')));
app.disable('x-powered-by');
app.use(session({
name: 'SESS_ID',
secret: config.secret,
resave: true,
saveUninitialized: true,
cookie: {
secure: false,
httpOnly: true,
maxAge: 5*60*1000 } //15minutes*60sec*1000ms
//cookie: {secure: false} //https = true, http=false
}));
app.use(csrf());
app.use(passport.initialize());
app.use(passport.session());
require('./config/passport')(passport);
app.use(function(req, res, next) {
res.locals._csrf = req.csrfToken();
next();
});
app.use('/', require('./routes/fileRoutes'));
app.use('/', require('./routes/authRoutes'));
app.listen(PORT,function(){
console.log("Server started at the port " + PORT);
});
routes/fileRoutes.js
app.get('/',function(req,res){
File.find(function(err, files){
res.render('views/layout',{files:files});
});
});
app.post('/addfile',upload,function(req,res){
if (req.fileValidationError) {
return res.end("Error PDF");
} else {
for (var i = 0; i < req.files.length; i++)
{
var files = new File ();
files.fieldname= req.files[i].fieldname;
files.originalname= req.files[i].originalname;
files.encoding= req.files[i].encodin;
files.path= req.files[i].path;
files.save(function(err, data){
});
}
res.redirect('/');
}
});
layout.pug
form#uploadForm(enctype='multipart/form-data', action='/addfile', method='post')
input(type='hidden', name='_csrf', value=_csrf)
input(type='file', name='userPhoto', multiple='')
input(type='submit', value='Upload Image', name='submit')
input#random(type='text', name='random')
I see you have:
input(type='hidden', name='_csrf', value=_csrf)
What is the value for if you console.log(_csrf)? I also noticed you didn't put that one in quotes.
I am trying to print out a session object in middleware of an ExpressJS framework. I am new to a session with express and want to see if the object saves to Redis which I have configurated in the app.js file
[index.js (router)]
router.use('/', function(req, res, next) {
req.session.user = {};
req.session.user.browserInformation = req.headers['user-agent'];
console.log(req.session);
next();
});
router.get('/', function(req, res, next) {
res.render('index.html');
});
[The app.js File:]
'use strict';
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const bodyParser = require('body-parser');
const session = require('express-session');
const redis = require('redis');
const redisStore = require('connect-redis')(session);
const client = redis.createClient();
const app = express();
const _Utils = require('./application/_Utils');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(bodyParser.urlencoded({
extended: false
}))
app.use(bodyParser.json())
app.use(express.static(path.join(__dirname, 'views')));
//require('./config/router')(app);
let indexRouter = require('./routes/index');
app.engine('html', require('ejs').renderFile)
// 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');
});
app.use(session({
secret: _Utils.getHashedValue(),
store: new redisStore({
host: '127.0.0.1',
port: 6379,
client: client,
ttl: 3600000
}),
saveUninitialized: false,
resave: false,
cookie: {
expires: new Date(Date.now() + 3600000),
maxAge: 3600000
},
}));
module.exports = app;
An issue I am having is that nothing is printing or Redis is empty when I execute KEYES * command in the terminal client interface
EDIT: Added a whole app.js file
in my case code is worked:
console.log(req.session);
Also use this in attend some information to session use this:
req.session.mail="a#b.com";
İf you are in localhost add this unsecure cookie options in our code. For example:
app.use(session({ secret: 'GttiginYagmurlagelkuskunumyagmuralara' ,resave: true,
saveUninitialized: true,
cookie: { secure: false,maxAge: 3600000}}));
Code:
Express.js
'use strict';
module.exports = function(app, io, server) {
var express = require('express');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride('X-HTTP-Method-Override'));
// Redis
const redis = require('./utils/redis.js')();
app.set('redis', redis);
let isSessionCreated = false;
app.use('*', (req, res, next) => {
if(!isSessionCreated) {
isSessionCreated = true;
require('./middleware/sessionConfig.js')(app);
next();
}
});
// Passport
require('./middleware/passport.js')(app);
// Start Socket
require('./middleware/startSocket')(app, io);
app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/dist'));
// Start Webpack
require('./webpack/startWebpack.js')(app);
// routes ==================================================
require('./routes/routes')(app); // configure our routes
require('../config/webpack.dev.js');
}
redis.js
'use strict';
const redis = require('redis'),
session = require('express-session'),
redisStore = require('connect-redis')(session),
redisClient = redis.createClient(),
uuid = require('uuid'),
cookieParser = require('cookie-parser');
module.exports = function() {
console.log('Redis started');
// Connects to Redis Store
const sessionStore = new redisStore({
host: '127.0.0.1',
port: 6379,
client: redisClient,
ttl : 3600000
});
redisClient.on('error', (err)=> {
console.log('could not connect ', err);
});
// Checks for Redis Connection
redisClient.on('connect', ()=> {
console.log('redis connected');
});
return {
set: function(obj) {
console.log('set called: ', obj);
redisClient.set(obj.id, obj.token);
},
sessionStore
}
}
sessionConfig.js
'use strict';
module.exports = function(app) {
const cookieParser = require('cookie-parser'),
session = require('express-session'),
uuid = require('uuid');
// Sets up Express Session
app.use(cookieParser());
console.log('session created');
let redis = app.get('redis');
app.use(session({
name: 'irelief',
secret: 'irelief',
store: redis.sessionStore,
cookie: {
cookieName: 'xyz',
httpOnly: false,
secret: 'irelief',
secure: false,
maxAge: 360000000
},
genid: function(req) {
return uuid.v4();
},
saveUninitialized: false,
resave: true,
rolling: true
}));
}
OUTPUT OF req.session on app.get('/', (req, res))
session: Session {
cookie:
{ path: '/',
_expires: 2017-07-30T22:38:34.653Z,
originalMaxAge: 360000000,
httpOnly: false,
cookieName: 'xyz',
secret: 'irelief',
secure: false } }
I have tried all that was said across any communities, nothing helps so far.
The same problem persists with passport.js
Any help will be awesome
I am currently working on a basic app where a user needs to authenticate (with passportJS) and then send a message to my server with socket.io. Here is the nodeJS code:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressSession = require('express-session');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var routes = require('./routes/index');
var api = require('./api/index');
var auth = require('./routes/auth');
var session = expressSession({secret: 'mySecret', resave: true, saveUninitialized: true});
var port = normalizePort(process.env.PORT || '3000');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var sharedsession = require('express-socket.io-session');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.set('port', port);
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session);
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/bower_components', express.static(path.join(__dirname, 'bower_components')));
app.use('/', routes);
app.use('/api', api);
app.use('/auth', auth);
// passport config
var User = require('./models/user');
passport.use(new LocalStrategy({
usernameField: 'email'
}, User.authenticate()));
passport.use(require('./strategies/facebook'));
passport.use(require('./strategies/google'));
passport.serializeUser(function(user, done) {
done(null, { id: user._id });
});
passport.deserializeUser(function(obj, done) {
done(null, obj);
});
io.use(sharedsession(session, {
autoSave:true
}));
io.on('connection', function(socket) {
console.log('user connected');
console.log(socket.handshake.session);
socket.on('message-new', function(data) {
console.log('receiving message to create');
console.log(socket.handshake.session);
});
socket.on('disconnect', function() {
console.log('user disconnected');
});
});
server.listen(port);
So as you can see I use express-socket.io-session to be able to access the session in my socket and it is supposed to be the same than req.session. So at first when a user is connected to the socket.io (but not authenticated), his socket.handshake.session is equal to req.session so:
Session {
cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true } }
once he authenticates, req.session becomes:
cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true },
passport: { user: { id: 56a13e58150f42fc29b44b7a } } }
but when I emit a message-new from the client and that it displays socket.handshake.session, it is still equals to
Session {
cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true } }
So the socket's session was not updated when req.session was. How can I change this behavior? I need to be able to know in my socket if the user is connected or not...
Inside your event listener 'new message' you can tell the session to reload, the docs don't explicitly say this, but it shares some of the same methods with the express-session
Inside your event listener you can tell session to reload
socket.handshake.session.reload(function(err) {
// this will give you the update session info
}
With the 'express-session' you can use the same method as in the docs