NodeJS procedure execution flow - node.js

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).

Related

Router.express() -> What is the proper way for expressing router.use?

For router.use, it does not work like this anymore:
router.use("/api", apiRoutes);
Instead an error is thrown:
throw new typeerror('router.use() requires a middleware function but got a ' + gettype(fn))
How do I re-purpose that expression so that it works? I have not found any examples that were useful so far. Here is some of my sample code:
routes/index.js (this does not work)
const path = require("path");
const router = require("express").Router();
const apiRoutes = require("./api");
// API Routes
router.use("/api", apiRoutes);**// this throws an error**
router.use(function(req, res) {
res.sendFile(path.join(__dirname, "../client/build/index.html"));
});
module.exports = router;
Here is an example of my attempt to re-purpose but I do not think it's correct:
var path = require("path");
var router = require("express").Router();
var apiRoutes = require("./api");
//API Routes
//authRouter.use(require('./authenticate').basic(usersdb))
//router.use("./api", apiRoutes);
console.log("Hitting API routes...")
router.use("./api", function(req, res, next) { **//re-purpsose attempt here**
res.send(apiRoutes)
console.log("API Routes:", apiRoutes)
next()
});
console.log("API Routes hit")
// //If no API routes are hit, send the React app
// router.use(function(req, res) {
// res.sendFile(path.join(__dirname, "../client/public/index.html"));
// });
module.exports = router
This is the overall error I'm getting (404 returned):
GET /api/website_1_function_call/scrape 404 4.004 ms - 173
I know that this may be due to something else indirectly but I really am not sure about the router.use part.
I know for sure that the routes are not being hit properly and would like to fix.
Any advice would be appreciated. Thank you in advance.
Here is more code:
server.js
require("dotenv").config();
var express = require("express");
var cors = require('cors');
var bodyParser = require('body-parser');
var logger = require("morgan");
//const mongoose = require("mongoose");
var db = require("./models")
var routes = require("./routes");
var app = express();
var PORT = process.env.PORT || 3001;
var path = require('path');
//Define middleware here
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(bodyParser.json());
//Serve up static assets (usually on heroku)
if (process.env.NODE_ENV === 'production') {
app.use(express.static("client/build"));
}
app.use(cors());
app.use(logger("dev"));
//Add routes, both API and view
app.use(routes);
//replaced with below:
//app.use(app.router);
//routes.initialize(app);
// //Connect to the Mongo DB
// mongoose.connect(process.env.MONGODB_URI || "mongodb://localhost/kaibru");
var syncOptions = { force: false };
// If running a test, set syncOptions.force to true
// clearing the `testdb`
if (process.env.NODE_ENV === "test") {
syncOptions.force = true;
};
// Starting the server, syncing our models ------------------------------------/
db.sequelize.sync(syncOptions).then(function() {
app.listen(PORT, function() {
console.log(
"==> 🌎 Listening on port %s. Visit http://localhost:%s/ in your browser.",
PORT,
PORT
);
});
});
// //Start the API server
// app.listen(PORT, function() {
// console.log(`🌎 ==> API Server now listening on PORT ${PORT}!`);
// });
routes/index.js
var path = require("path");
var router = require("express").Router();
var apiRoutes = require("./api");
//API Routes
//authRouter.use(require('./authenticate').basic(usersdb))
//router.use("/api", apiRoutes);
console.log("Hitting API routes...")
router.use("/api", function(req, res, next) { // this is my re-purpose
attempt
apiRoutes
console.log("API Routes:", apiRoutes)
// next()
}); // this is my r-purpose attempt
console.log("API Routes hit")
// //If no API routes are hit, send the React app
// router.use(function(req, res) {
// res.sendFile(path.join(__dirname, "../client/public/index.html"));
// });
module.exports = router
routes/api/index.js
var router = require("express").Router();
require("./website_1");
var website_1Routes = require("./website_1_function_call");
//const userRoutes = require("./user");
//Website_1 routes
//http://localhost:3000/api/website_1_function_call/scrape
//authRouter.use(require('./authenticate').basic(usersdb))
//router.use("/website_1_function_call", website_1Routes);
//experimental use
router.use("/website_1_function_call", function(req, res, next) { // this is my re-purpose attempt
website_1Routes
console.log("website_1Routes:", website_1Routes)
// next()
}); //this is my re-purpose attempt
//router.use("/user", userRoutes);
module.exports = router
routes/api/website_1_function_call.js
require("./website_1");
require("./website_1_db");
require("./website_1_router");
//Call scrape functions from website_1 file
mainscrape();
//specificScrape() //let's leave this one dormant for now
//Now for saving to database
saveToDatabase();
//Now for the routes
routing();
I think my re-purpose attempt worked ( I removed next() since there are no defined routes right after). It seems to be processing. However, now my response hangs and this happens:
GET /api/website_1_function_call/scrape - - ms - -
This prints in the browser console:
GET http://localhost:3000/api/website_1_function_call/scrape
net::ERR_EMPTY_RESPONSE
0.chunk.js:871 Uncaught (in promise) Error: Network Error
at createError (0.chunk.js:871)
at XMLHttpRequest.handleError (0.chunk.js:366)
So now I think my scraper code and my code to update the database does not work.
Scrape function code:
//var express = require("express");
var router = require("express").Router();
require("../../controllers/website_1controller");
//requiring this website's models
var Items_1 = require("../../models/website_1");
//require("./website_1_db");
//require("./website_1_router");
// Our scraping tools
// Axios is a promised-based http library, similar to jQuery's Ajax method
// It works on the client and on the server
var axios = require("axios");
var cheerio = require("cheerio");
mainscrape = function() {
//Now to configure the routes
router.get("/scrape", function(req, res) {
//instead of simple res.render, user router.get
console.log("scraping started...");
//Grab the html body with axios
axios.get("url placeholder").then(function(response) {
//Load to cheerio and save to $ selector
console.log("Scraping all greenheartshop mainpage...");
var $ = cheerio.load(response.data);
var output = [];
var promises = [];
//Now we need to grab the title reference for each article
$("article").each(function(i, element) {
//save empty result object
var result = {};
//thumbnail
result.thumbnail = $(this)
//.children("article.product-grid-item.product-block").html()
.children("figure.product-item-thumbnail")
.children("a")
.attr("href")
//console.log("result thumbnail")
//console.log(result)
console.log(result.thumbnail)
var result = {}
//details
result.detail= $(this)
//.children("product-item-mask").html()
.children("div.product-item-details")
// .children("div.product-item-brand")
// .children("h5.product-item-title")
// .children("a")
// .children("div.product-item-price")
//.children("product-price-line")
//.children("price-value")
.text()
//result.detail = result.detail.trim();
//console.log("result detail")
//console.log(result)
console.log(result.detail)
//Capture the scraped data and save to database
console.log("Capturing Scrape")
if(result.detail !== '') {
var promise = Items_1
.saveToDatabase(result, result, {upsert:true, new:true})
console.log("saveToDatabase");
promises.push(promise);
}
Promise.all(promises).then((data) => {
res.json(data);
});
//saveToDatabase();
// if (result.thumbnail !== {} && result.detail !== "") {
// var promise = Items_1
// // .items_1_create({
// // resultThumbnail: result.thumbnail,
// // resultDetails: result.detail
// // })
// promises.push(promise)
// // .then(dbModel => output.push(dbModel));
// Promise.all(promises).then((data) => {
// res.json(data)
// })
// }
});
});
//Now to CREATE the results using controller file
// console.log("creating items in the database now...")
// router.post('/scrape', website_1Controller.items_1_create);
//Now to display the results
// console.log("Items now being displayed...")
// router.get('/scrape/display', website_1Controller.items_1_list)
});
}
module.exports = router;
module.exports = mainscrape;
module.exports = specificScrape;
Code to update the database:
require("../../controllers/website_1controller");
require("./website_1");
var Items_1 = require( "../../models");
//After scraping the main page, the following function is to save to the
database
saveToDatabase = function() {
//prepare the data
var result = {}
var dataToStore = Items_1.items_1_create
console.log(dataToStore)
//console.log(items_1_create)
//insert data to the database
// dataToStore.save().// We will not sue this part for now
// then(() => {
// console.log("Data successfully saved");
// }).catch(err => {
// console.log("Error: ", err);
// });
}
module.exports = saveToDatabase;
Code for final routing (after scrape is complete)
var website_1Controller = require("../../controllers/website_1controller");
var router = require("express").Router();
routing = function() {
//Now to CREATE the results using controller file
console.log("creating items in the database now...")
//router.route("/browse")
router.post('/browse', website_1Controller.items_1_create);
router.get('/browse', website_1Controller.items_1_list);
//Now to display the results
console.log("Items now being displayed...")
//router.route("/browse:search")
router.get('/:search', website_1Controller.items_1_specific);
};
require("./website_1");
module.exports = routing;
module.exports = router;
models
'use strict';
// Dependencies
// =============================================================
// Sequelize (capital) references the standard library
//var Sequelize = require("sequelize");
// sequelize (lowercase) references our connection to the DB.
//var sequelize = require("../config/connection.js");
// Creates a "Items_1" model that matches up with DB
module.exports = function(sequelize, DataTypes) {
var Items_1 = sequelize.define("Items_1", {
// the routeName gets saved as a string
detail: DataTypes.STRING,
// the name of the character (a string)
thumbnail: DataTypes.BLOB,
// the character's role (a string)
//role: Sequelize.STRING,
// the character's age (a string)
//age: Sequelize.INTEGER,
// and the character's force points (an int)
//forcePoints: Sequelize.INTEGER
}, {
// disable the modification of tablenames; By default, sequelize will
automatically
// transform all passed model names (first parameter of define) into
plural.
// if you don't want that, set the following
freezeTableName: true
});
return Items_1;
//Syncs with DB
//Items_1.sync();
// Makes the Items_1 Model available for other files (will also create a table)
};
controller
// *********************************************************************************
// website_1controllers.js - this file offers a set of routes for displaying and saving data to the db
// *********************************************************************************
// Dependencies
// =============================================================
var db = require("../models");
//display results for mainpage scrape
exports.items_1_create = function(req, res) {
db.Items_1.findOneAndUpdate(req.body, req.body, {upsert: true, new:
true})
.then(dbModel => res.json(dbModel))
.catch(err => res.status(422).json(err))
console.log("findOneAndUpdate complete")
},
exports.items_1_list = function(req,res) {
db.Items_1.findAll({})
},
exports.items_1_specific = function(req,res) {
db.Items_1.findById(req.params.search)
},
function(err, results) {
if (err) { return next(err); } //Error in API usage.
if (results.result.thumbnail==={} && results.result.detail==="") {//No
Results.
var err = new Error('Results not found');
err.status = 404;
return next(err)
}
//Successful, so render
res.render("click_results", { title: 'Click Results', resultThumbnail:
result.thumbnail, resultDetails: result.detail });
}
So the new issue is that the response hangs. I think it's because the code to update the database does not work (using sequelize). Let me know if anything else is needed and thank you in advance.
Thanks for all of the input everyone. After reviewing I found out that the function itself does not have to be re-purposed as I initially thought... I didn't know that if, for example, you are using "router.use("/directoy", directory) and you are using it in succession to point to different directories, the final directory hit must have a defined route like router.get(). I modularized my code to the point where the final directory was just a list of functions (one of these functions had the router.get method). This did not work. When I point the file directly to the code containing the router.get method, my scraped data returns to the terminal. Just thought I'd share my findings at least because I didn't know this at all . Many thanks to #mehta-rohan and #Anand Undavia for the insights. I'm still trying to get the data to render to the page but that's a different problem altogether.

Node.js Express Serve static files only with SIMPLE authentification

I've a problem since two days ago now.
I just want an authentification on my static files.
I look at a lot of post on the internet and nothing answer my question simply.
I try to use basic-auth, but it has no effect on my webpages.
I just want a simple dialog box before open my static pages that ask name and password and in my server.js just a thing like : if name == 'foo' and password =='pwd' then "send my static content".
But it seems to be not simple as it might be.
There is my code :
/***************************************************************************/
//Server Node.js
/** ************************************************************************ */
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
// Routers
var router = express.Router();
var mongoose = require("mongoose");
mongoose.connect('mongodb://localhost:27017/mydb');
var conn = mongoose.connection;
var assert = require("assert");
var basicAuth = require('basic-auth');
var auth = function (req, res, next) {
function unauthorized(res) {
res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
return res.send(401);
};
var user = basicAuth(req);
if (!user || !user.name || !user.pass) {
return unauthorized(res);
};
if (user.name === 'foo' && user.pass === 'bar') {
return next();
} else {
return unauthorized(res);
};
};
app.use('/', auth);
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({"extended" : false}));
router.route("/data").get(function(req, res) {
// A non static route
});
}).post(function(req, res) {
// A non static route
});
router.route("/data/:id?").get(function(req, res) {
// A non static route
});
router.route("/remove/:id?").get(function(req, res) {
// A non static route
});
app.use('/', router);
app.listen(8080);
console.log("Listening to PORT 8080");
Thanks.
Have a nice day.

Can not get any page after running node server in Ubuntu

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.

MemoryStore in node.js

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.

Passport + Socket.io get logged user id

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

Resources