I'm making a Node.js app and I need to create a new document in mongoDB inside socket.io.
I have to insert the logged in user in the new document.
How can I access the session variable inside socketio ?
// INCLUDE MODULES =======================================================
var SocketIOFileUpload = require("socketio-file-upload");
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var socketio = require('socket.io');
var Twig = require('twig');
var twig = Twig.twig;
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var Cookies = require( "cookies" );
var flash = require('connect-flash');
var configDB = require('./config/database.js');
var connect = require('connect');
var ImageFile = require('./app/models/image');
// Assets ================================================================
app.use(express.static(path.join(__dirname, 'public')));
app.use(connect.favicon(path.join(__dirname, 'public/images/favicon.ico')));
// Start mongoose
mongoose.connect(configDB.url);
// USER MANAGEMENT =======================================================
require('./config/passport')(passport); // pass passport for configuration
app.use(connect.logger('dev')); // log every request to the console
app.use(connect.cookieParser()); // read cookies (needed for auth)
app.use(connect.json()); // to support JSON-encoded bodies
app.use(SocketIOFileUpload.router); //socket io file upload
app.use(connect.urlencoded()); // to support URL-encoded bodies
app.set('view engine', 'twig'); // set up twig for templating
app.use(connect.session({ secret: 'ilovescotchscotchyscotchscotch' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash());
// Some more code ...
//SOCKET IO =======================================================
//Quand on client se connecte, on le note dans la console
var io = socketio.listen(server);
io.sockets.on("connection", function(socket){
// Make an instance of SocketIOFileUpload and listen on this socket:
var session = socket.handshake.session;
var uploader = new SocketIOFileUpload();
uploader.dir = "/LeafStore/public/uploads";
uploader.listen(socket);
console.log(socket.handshake.user);
// Do something when a file is saved:
uploader.on("saved", function(event, socket){
console.log(event.file);
});
// Do something when a file is saved:
uploader.on("complete", function(event){
console.log("saving file" + name);
console.log(event);
var name = event.file.name;
var imageData = {
name: name
, type: "image"
, userId: ""
, creationDate: new Date()
};
var newImage = new ImageFile(imageData);
newImage.save( function(error, data){
if(error){
throw error;
}
else{
}
});
// save the user
newImage.save(function(err) {
if (err)
throw err;
});;
});
// Error handler:
uploader.on("error", function(event){
console.log("Error from uploader", event);
});
});
// LISTEN SERVER =======================================================
server.listen(80);
I found a temporary solution :
I emit the user Id in my views :
socket.emit('userId', $("#userId").val());
Then I set the socket.userId var :
socket.on('userId', function(userId){
socket.userId = userId;
});
But it's probably unsafe
Related
In my project i am using nodejs (express), react js and socket.io to develop a chatting application. But i am not able to get "correct sessionid" inside my socket function (io.use).
In server.js file there are routes and functions to handle socket connections.
In my project i had started my express-session inside login.js file.
Then after successfull login...i am redirecting to home.js, which intern returns home.html.
home.html contains js file, which is having react code and also have socket connections.
server.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var path = require('path');
var DIST_DIR = path.join(__dirname, "bin");
var express = require('express');
//Getting session store
var session = require('express-session');
var cookieParser = require('cookie-parser');
var sessionStore = new session.MemoryStore();
var handshakeData ={};
var cookie = require('cookie');
//Importing routes
var login = require('./routes/login.js');
var registration = require('./routes/registration.js');
var home = require('./routes/home.js');
//Getting cookies from request header. so that from it we can get sessionid.
io.use(function(socket, next) {
handshakeData = socket.request;
var cookies = cookie.parse(handshakeData.headers.cookie);
//Bringing sessionid and storing in a global variable
console.log("***********************Server*********************");
console.log("");
console.log('All cookies parsed in io.use ( %s )', JSON.stringify(cookies));
handshakeData.sessionID = cookies['connect.sid'].split('.')[0].split(':'[1];
console.log('All cookies parsed at server ( %s )', JSON.stringify(cookies));
console.log('Session id at server cookie value in io.use( %s )',
JSON.stringify(handshakeData.sessionID));
next();
});
//Bringing session data by sending "sessionid" to sessionStore
(MemoryStore)place
io.on('connection', function(socket){
sessionStore.get(handshakeData.sessionID, function (err, session) {
handshakeData.session = session;
//Now we can retrieve all session data. But sessionID sent was
not correct
});
console.log('user connected');
socket.on('new message', function(msg){
console.log('Server recieved new message: '+msg);
io.emit('new message', msg);
});
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
app.use('/', login);
app.use('/registration', registration);
app.use('/home', home);
http.listen(8080, function(){
console.log("listening on port 8080");
});
login.js
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false })
var cookieParser = require('cookie-parser');
var session = require('express-session');
var sessionStore = new session.MemoryStore();
var login_success = 0;
router.use(cookieParser());
router.use(session({ cookie: {
maxAge : 24*60*60*1000
},
store: sessionStore,
saveUninitialized: true,
resave: true,
secret: '1234567890QWERT'
}));
router.get('/', function(req, res){
console.log("Actual session id before login: "+ req.sessionID);
//Clearing cookies at client side.
res.clearCookie("login_message");
res.clearCookie("connect.sid");
res.clearCookie("io");
res.clearCookie("user_name");
res.clearCookie("user_id");
if (login_success == 2)
{
res.cookie('login_message', 'incorrectCredentials');
login_success = 0;
}
res.sendFile(path.join(SRC_DIR,"login.html"));
// res.sendFile(path.join(__dirname, '../bin', 'login.html'));
});
router.post('/', urlencodedParser, function(req, res){
console.log("database called");
//Fetching form data
var username = req.body.loginusername;
var password = req.body.loginpassword;
//Connection string to datanbase
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/WebChat";
//Comparing username and password.
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var query = { email: username, password: password };
db.collection("Profile").find(query).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
if (result.length != 0)
{
console.log("login success");
login_success = 1;
//Setting session variables
req.session.userid = username;
req.session.username= result[0].firstname;
console.log("***********************Login*********************");
console.log("");
console.log("Actual session id at login: "+ req.sessionID);
console.log("Session userid at server set to :"+ req.session.userid);
console.log("Session name at server set to :"+ req.session.username);
//res.sendFile(path.join(SRC_DIR,"home.html"));
// res.status(200).send(req.session);
console.log("Session reload called");
res.redirect('/home');
}
else
{
//**It is for when user come to login page with entering wrong credentials
login_success = 2;
console.log("login failed");
res.redirect('http://localhost:8080');
}
});
});
});
//export this router to use in our server.js
module.exports = router;
home.js
var express = require('express');
var router = express.Router();
var path = require("path");
var SRC_DIR=path.join(__dirname, "../src/views");
var session = require('express-session');
cookie = require('cookie');
var cookieParser = require('cookie-parser');
var sessionStore = new session.MemoryStore();
var handshakeData ={};
router.use(cookieParser());
router.use(session({ cookie: {
maxAge : 24*60*60*1000
},
store: sessionStore,
saveUninitialized: true,
resave: true,
secret: '1234567890QWERT'
}));
router.get('/', function(req, res){
//setting cookie at client side
res.clearCookie("user_id");
res.clearCookie("user_name");
res.cookie('user_id', req.session.userid);
res.cookie('user_name', req.session.username);
// res.status(200).send(req.session);
console.log(" session reload called");
setTimeout(function(){
res.sendFile(path.join(SRC_DIR,"home.html"));
}, 5000);
console.log("***********************Home*********************");
console.log("");
console.log("Actual session id at home: "+ req.sessionID);
console.log("Cookie userid at client set to :"+ req.session.userid);
console.log("Cookie username at client set to :"+ req.session.username);
});
//export this router to use in our server.js
module.exports = router;
home.jsx (client side file)
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {messages: [],socket: io.connect('http://localhost:8080')};
this.send = this.send.bind(this)
}
}
export default Home
Ouput when exicuting "node server.js":
output
In the above output...
1. login page we got two different session ids (before login and after login).I don't know why this is happening
2. While accessing the session variable inside "server.js", in "io.use" function... we again getting old session id, which was set before login.But with this i can't get my session variable. Because i need to pass new session variable in order to access session variable inside sessionStore.get.
Please help. i have been trying this for 3 days.
Thanks in advance.
I'm trying to create a private tchat room using the concept of socket.io rooms. When the user clicks on a name of another user, a comparaison will start,if there is a room which contains both users, then it will join the room, otherwise a new room with both users will be created.
When a message arrives, the message is sent to the corrsponding room, but my code doesn't work: the comparaison is done, the corresponding ids are found, but the messages are send for everyone connected to the tchat.
Here is the code of the server
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var port = process.env.PORT || 8080;
var cookieParser = require('cookie-parser');
var session = require('express-session');
var morgan = require('morgan');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var passport = require('passport');
var flash = require('connect-flash');
//session-store
var MongoStore = require('connect-mongo')(session);
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
require('./config/passport')(passport);
var Room = require('./app/models/room');
var User = require('./app/models/user');
//session
var sessionMiddleware = session({
secret: 'anystringoftext',
saveUninitialized: true,
resave: true,
store: new MongoStore({
mongooseConnection: mongoose.connection
}),
ttl: 2 * 24 * 60 * 60
});
//fonction btoa
var btoa = require('btoa');
var atob = require('atob');
//session with socket.io
io.use(function(socket, next) {
sessionMiddleware(socket.request, {}, next);
});
io.on('connection', function(socket) {
socket.on('startchat', function(name) {
//my id
var idUser = socket.request.session.passport.user;
//search for my name
User.findById(idUser, function(err, user) {
if (err) throw err;
if (user) {
//my name
nameUser = user.local.username;
if (name < nameUser) {
var users = name + ',' + nameUser;
} else {
var users = nameUser + ',' + name;
}
//encrypt the string
var roomid = btoa(users);
//searching fo ra corresponding id
Room.find(function(err, room) {
if (err) throw err;
if (room) {
var dRoom = '';
room.forEach(function(room) {
var idRoom = atob(room.id).split(',');
//comparaison
if ((idRoom[0] == nameUser && idRoom[1] == name) || (idRoom[0] == name && idRoom[1] == nameUser)) {
dRoom = room.id;
console.log(idRoom, room.id);
//join the room
socket.join(dRoom);
}
});
if (dRoom == '') {
//we didn't find an id which corresponds so we create a room with this id
dRoom = roomid;
var newroom = new Room({
id: roomid
});
newroom.save();
console.log('created');
console.log(atob(roomid).split(','));
console.log(roomid);
//join the room
socket.join(roomid);
}
}
//when msg is emitted
socket.on('message', function(msg) {
console.log('message', dRoom);
//emit the msgs to this room
io.sockets.in(dRoom).emit('msg', msg);
});
});
}
});
});
app.use(express.static('public'));
app.use(morgan('dev'));
app.use(cookieParser());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(sessionMiddleware);
//passport and sessions
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
app.set('view engine', 'ejs');
require('./app/routes.js')(app, passport);
server.listen(port, function() {
console.log('Server running on port: ' + port);
});
the client.js
$(document).ready(function(){
var socket = io();
socket.on('connect', function() {
// Connected, let's sign-up for to receive messages for this room
$('#chat').hide();
var start;
window.start = function (id,name){
$('#chat').show();
$('#chatHeader').html(name);
socket.emit('startchat', name);
}
$('#send').submit(function(event){
event.preventDefault(); //empeche la page de se recharger
var msg = $('#message').val();
if(msg !== ''){
socket.emit('message', msg);
}
$('#message').val('');
});
});
socket.on('msg', function(msg){
$('.messages').append('<div>'+ msg + '</div>');
});
});
I am new to Nodejs and aslo coming from a procedural language background so I have this need to know the execution flow of my code. I have a general question about the flow of Nodejs procedures. This is the scenario:
The code structure:
Appnamefolder
...standard node folders(.idea,css,fonts,etc)
...model
....database.js (connect to db and execute db queries)
...public
...routes
....users.js (GET and POST procedures....calls db queries via module.export)
...views
...app.js
...other js files
The question concerns the database. Since the DB connect is not in the app.js file but in a .js file in the model folder at what point is the DB connection made? and is a connection made every time a DB query is made?
What I hope to happen is that the DB connect is made one time and remain connected until the app is terminated. I tried putting the DB connect in app.js but I get an error when I attempt a DB query so I have to place the DB connect in the same file as the DB queries......Somehow this seems wrong to me. Can anyone explain how node handle this flow?....will be appreciative of any assistance.
EDIT: HERE IS A SAMPLE OF THE CODE
app.js
var express = require('express');
var path=require('path');
var bodyParser = require('body-parser');
var cookieParser=require('cookie-parser');
var expressSession=require('express-session');
var expejs = require('ejs');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var expressSession = require('express-session');
var expressLayouts=require("express-ejs-layouts") // add this requirement
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var crypto = require("crypto");
var loaddealerTable=require('./loaddealerTable');
//var neo4j = require('neo4j-driver').v1;
// var neo4jdb = neo4j.driver("bolt://localhost:7474", neo4j.auth.basic("neo4j", "password"),
// {
// trust: "TRUST_ON_FIRST_USE",
// encrypted:true
// });
//***************Notifications Permission*******
var routes = require('./routes/index');
var users = require('./routes/users');
var csocket=require('./socketconnections');
var app=express();
var server=require('http').createServer(app);
sockets = require('./socketserver');
//rpaMessageWaiting = require('./getRPAmessages');
//var io=require('socket.io').listen(server);
// View Engine
app.set('views', path.join(__dirname,'views'));
app.set('view options', { layout:'layout.ejs' });
app.set('view engine','ejs');
//bodyParsers middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(expressLayouts);
//set up public folder
app.use(express.static(path.join(__dirname, '/public')));
// set express session with secret
app.use(expressSession({ secret: process.env.SESSION_SECRET || 'secret',
resave: true,
saveUninitialized: true
}));
// Passport initialization
app.use(passport.initialize());
app.use(passport.session());
//Express Validitor...validate inputs..taken from github middleware options
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 middleware
app.use(flash());
// set global variables for flash messages
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();
});
// Middelware for route files
app.use('/', routes);
app.use('/users', users); //need to check routing
sockets.startSocketServer(server);
//load dealer table
console.log("load dealer table");
**loaddealerTable(); //First call on the DB**
//============socket io listening=======================
app.set('port',(process.env.PORT|| 3000));
server.listen(app.get('port'), function()
{
console.log('Server started on port '+app.get('port'));
// console.log('Server started on port .....');
// app.get('/index',function (req,res) {
// // body...
// res.render(__dirname+'/index');
});
loaddealertable.js
var loaddealerTable=function()
{
var memorytbl=require('./memorytables');
var User = require('./model/user');
var getHashKey=require('./gethashkey');
const hashMax=1000;
console.log("call get dealers from DB");
User.getallDealers(function(err,dealerFound,result)
{
if (dealerFound)
{
//
for (i=0; i< result.records.length; i++)
{
memorytbl.Dealer.email =result.records[i].get(0).properties.email;
memorytbl.Dealer.name =result.records[i].get(0).properties.name;
memorytbl.Dealer.telephone =result.records[i].get(0).properties.storenumber;
memorytbl.Dealer.creditcard =result.records[i].get(0).properties.creditcard;
memorytbl.Dealer.delivery =result.records[i].get(0).properties.delivery;
memorytbl.Dealer.location =result.records[i].get(0).properties.location;
memorytbl.Dealer.rating =result.records[i].get(0).properties.rating;
var hashIndex = getHashKey(memorytbl.Dealer.email ,hashMax);
memorytbl.DealersQ[hashIndex]=memorytbl.Dealer;
} //end of for i
} //end of if....
else
{
console.log("No dealers found....table is empty");
}
}) //end of loaddealers table db call
} //end of load dealers table function
module.exports=loaddealerTable;
user.js
var express = require('express');
var bcrypt = require('bcryptjs');
var router = express.Router();
var neo4j = require('neo4j-driver').v1;
var driver = neo4j.driver("bolt://localhost", neo4j.auth.basic("neo4j", "password"));
var session = driver.session();
//============Load Memory Tables=========================
router.getallDealers=function(callback) {
session
.run ("MATCH (user:Dealer) RETURN user")
.then (function(result)
{
if ( !result.records[0])
{
console.log("No Dealers Found");
session.close();
if (typeof callback==="function") {
return callback(null,false,result);
}
} // end of if not found
else
{
console.log("Dealer Found");
session.close();
if (typeof callback === "function")
{
return callback(null, true, result);
}
}
// or close session here??
}) //end of .then block
.catch(function(err)
{
console.log("DB call error: "+err);
}); //.then block
} //end of get dealers
For a start you have to understand that each file is a module.
Your app starts with running a single js file (module) like node app.js.
One module can load another module and another and so on.
Your folder structure does not have any effect on the order by itself. It all depends on your code and in what order do you load modules. While your sync code will run in the order you write it your async code will run in the future and you need to understand the event loop to understand what happens in your code.
From the small context you gave I guess you might tried to query your database before you connected to it. I don't see your code but it can happen regardless of where you connect (app.js file or another).
I uploaded all Node.js related file in Ubuntu server .i opened putty and typed my server's instance ip then started the server after moving to the uploaded file directory.The Node server is running successfully but when i tried to get the pages by typing the url e.g-*.*.*.*:8888 which contains the server's instance ip and port number no page is coming.It is throwing the message This webpage is not available ERR_CONNECTION_RESET.I am explaining my code and server's snap shot below.
server.js:
var port=8888;
var express=require('express');
var morgan = require('morgan');
var http=require('http');
var bodyParser= require('body-parser');
var methodOverride = require('method-override');
var mongo = require('mongojs');
var database='Oditek';
var collections=['video'];
var app= express();
var server=http.Server(app);
var io=require('socket.io')(server);
var db = mongo.connect("10.25.25.100:27017/"+database, collections);
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({ extended: false })) // parse application/x-www-form-urlencoded
app.use(bodyParser.json()) // parse application/json
app.use(methodOverride()); // simulate DELETE and PUT
db.on('ready', function () {
console.log('database connected')
});
app.get('/',function(req,res){
res.sendfile('view/login.html');
});
app.post('/login',function(req,res){
var username=req.body.username;
var password=req.body.userpassword;
if(username && password){
db.video.findOne({
username:username,
password:password
},function(err,doc){
if(doc){
console.log('login',doc);
res.send(doc);
}
if(err){
console.log('login12',err);
res.send("could not login");
}
});
}
});
app.get('/index',function(req,res){
res.sendfile('view/index.html');
});
app.get('/video',function(req,res){
res.sendfile('view/video.html');
});
app.get('/whiteboard',function(req,res){
res.sendfile('view/whiteboard.html');
});
//socket----programming//
var roomid;
var clients={};
io.on('connection',function(socket){
//console.log('socket id',socket);
if(socket.handshake.query.roomid){
roomid=socket.handshake.query.roomid;
}
var usertype=socket.handshake.query.usertype;
//var url=socket.handshake.headers.referer;
//var myString = url.substr(url.indexOf("?") + 1);
//var usertype=myString.substr(myString.indexOf("=")+1);
//console.log('usertype',usertype);
clients[usertype]={
"socket":socket.id
}
console.log('clients',clients['admin'].socket);
socket.on('admin-join',function(data){
if(data.IsJoinAdmin){
socket.join(roomid);
}
});
socket.on('user-join',function(data){
console.log('user wants to join',data);
//console.log('user type',clients);
if(data.isUserJoin){
io.sockets.connected[clients[data.usertype].socket].emit('user-already-joined',data);
socket.join(roomid);
}
});
socket.on('send-playing-video-request-to-users',function(data){
io.to(roomid).emit('sending-broadcasting',data);
});
socket.on('send-broadcasting-message',function(data){
io.to(roomid).emit('sending-broadcasting',data);
});
socket.on('share-white-board',function(msg){
io.to(roomid).emit('sharing-white-board',msg);
});
socket.on('disconnect', function() {
for(var user in clients) {
if(clients[user].socket === socket.id) {
delete clients[user];
io.to(roomid).emit('user-has-left',{userleft:true});
break;
}
}
})
});
server.listen(port);
console.log('server is listening on the port'+port);
Here i can not get the pages even if the server is running.Please help me to get the pages after running the node server.
I am working on implementing social network application using node.js and the source that I use is Building Node Application with MongoDB and Backbone' by Mike Wilson.However, I cannot figure out the how to resolve the error of the MemoryStore --var MemoryStore = require('connect').session.MemoryStore;
Also, I tried to comment it but the error with middleware appear
var Session = require('connect').middleware.session.Session;
Can I get your help please ?
Thanks in advance
Here is the code of app.js
var express = require('express');
var http = require('http');
var app = express();
var nodemailer = require('nodemailer');
var MemoryStore = require('connect').session.MemoryStore;
var dbPath = 'mongodb://10.168.122.123:27017/socialnet';
var fs = require('fs');
var events = require('events');
// Create an http server
app.server = http.createServer(app);
// Create an event dispatcher
var eventDispatcher = new events.EventEmitter();
app.addEventListener = function (eventName, callback) {
eventDispatcher.on(eventName, callback);
};
app.removeEventListener = function (eventName, callback) {
eventDispatcher.removeListener(eventName, callback);
};
app.triggerEvent = function (eventName, eventOptions) {
eventDispatcher.emit(eventName, eventOptions);
};
// Create a session store
app.sessionStore = new MemoryStore();
// Import the data layer
var mongoose = require('mongoose');
var config = {
mail: require('./config/mail')
};
// Import the model
var models = {
Account: require('./models/Account')(app, config, mongoose, nodemailer)
}
// Configure the application
app.configure(function(){
app.sessionSecret = 'SocialNet secret key';
app.set('view engine', 'jade');
app.use(express.static(__dirname + '/public'));
app.use(express.limit('1mb'));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({
secret: app.sessionSecret,
key: 'express.sid',
store: app.sessionStore
}));
mongoose.connect(dbPath, function onMongooseError(err) {
if (err) throw err;
});
});
// Import the routes located in ./routes
fs.readdirSync('routes').forEach(function(file) {
if (file[0] == '.') return;
var routeName = file.substr(0, file.indexOf('.'));
require('./routes/' + routeName)(app, models);
});
// -----
// GET /
// -----
app.get('/', function(req, res){
res.render("index.jade", {layout: false});
});
// -------------------
// POST /contacts/find
// -------------------
app.post('/contacts/find', function(req, res) {
var searchStr = req.param('searchStr', null);
if (null == searchStr) {
res.send(400);
return;
}
models.Account.findByString(searchStr, function onSearchDone(err, accounts) {
if (err || accounts.length == 0) {
res.send(404);
} else {
// TODO: Check if these accounts were already contacts
// if so, mark them as isContact so the views/Contact
// knows not to add a addButton
res.send(accounts);
}
});
});
// Let the server listen to 8000 (instead of the app)
app.server.listen(8000);
console.log('SocialNet listening to port 8000');
Your problem:
app.use(app.router)
, mounts your routes in that position in the call chain. You have it before your session middleware, so there is no req.session yet. When you leave it out, your routes will be positioned whenever you do your first app.get (or app.post and so on). If you still wish to control where your routes should be,
you can just:
move app.use(app.router) below the session middleware.