I'm connecting Socket in my App but the configuration is mismatched because of which socket is not connecting. What could be the problem? I'm referring to "Mastering Web Application Development with Express" for structuring
app.js
var express = require('express');
var app = express();
var morgan = require('morgan'); //HTTP request logger middleware for node.js
var flash = require('connect-flash');
var multiparty = require('connect-multiparty');
var cookieParser = require('cookie-parser');
var cookieSession = require('express-session');
var bodyParser = require('body-parser'); //Node.js body parsing middleware
var methodOverride = require('method-override');
var errorHandler = require('errorhandler');
var config = require('./config.js');
var passport = require('passport');
var fs = require('fs');
var sessionStore = new cookieSession.MemoryStore();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
morgan.token('id', function getId(req) {return req.id })
var accessLogStream = fs.createWriteStream(__dirname + '/log/systemAccessWithToken.log', {flags: 'a'})
app.use(assignId)
app.use(morgan(':id :method :url :response-time', {stream: accessLogStream}))
function assignId(req, res, next) {
next()
}
app.use(bodyParser.json()); //middleware that only parses json
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride(function(req, res) {
if (req.body && typeof req.body === 'object' && '_method' in req.body) {
var method = req.body._method;
delete req.body._method;
return method;
}
}));
app.use(cookieParser());
app.use(cookieSession({
store: sessionStore,
secret: config.sessionSecret,
cookie: {maxAge: config.sessionMaxAge}
}));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash());
if (app.get('env') === 'development') {
app.use(errorHandler());
}
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.set('Access-Control-Allow-Methods', 'GET, POST');
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.use(express.static(__dirname + '/public'));
require('./app/passport')(passport); // pass passport for configuration
var socketcon = require('./app/mainSocket.js');
socketcon.socketconfig(app, io, sessionStore, cookieParser);
require('./routes/controller.js')(app, passport); // load our routes and pass
server.listen(config.port);
mainSocket.js
var modules = require('../externalModules.js');
var dbConnection = modules.dbConnection;
var cryptography = modules.cryptography;
var onlineUsers = {};
var onlineUsersSocketid = {};
exports.socketconfig = function(app, io, sessionStore, cookieParser) {
io.set('authorization', function(data, callback) {
if (!data.headers.cookie) {
return callback('No cookie transmitted.', false);
}
cookieParser(data, {}, function(parseErr) {
if (parseErr) {
return callback('Error parsing cookies.', false);
}
var sidCookie = (data.secureCookies && data.secureCookies['myuser.sid']) || (data.signedCookies && data.signedCookies['myuser.sid']) || (data.cookies && data.cookies['myuser.sid']);
sessionStore.load(sidCookie, function(err, session) {
if (err || !session || !session.passport.user) {
callback('socket Not logged in.', false);
} else {
data.session = session;
socketSession = session;
console.log("socketSession value " + JSON.stringify(socketSession));
callback(null, true);
}
});
});
});
io.sockets.on('connection', function(socket) {
console.log("socket connected");
console.log("socket.id " + socket.id);
socket.encryptedUserid = socketSession.passport.user.userId;
var devicetype = "web";
var secUserSalt = socketSession.passport.user.salt;
socket.userid = cryptography.crypto.fnDecryption(
socket.encryptedUserid, secUserSalt);
var isMobile = socketSession.passport.user.isMobile;
var devicetype = "web";
if (isMobile) {
devicetype = "mobile";
}
socket.on('user:join', function() {
//==============================develpoment(Aug21)====================
if (socket.userid in onlineUsersSocketid) {
onlineUsersSocketid[socket.userid].sockets_ids
.push(socket.id);
onlineUsersSocketid[socket.userid].devicetype
.push(devicetype);
} else {
onlineUsersSocketid[socket.userid] = {
"sockets_ids": [socket.id], // array for all sockets id of this user
"devicetype": [devicetype]
}
}
console.log("onlineUsersSocketid " + JSON.stringify(onlineUsersSocketid));
});
socket.on('disconnect', function() {
delete onlineUsersSocketid[socket.userid];
});
});
} // end of export module
What could be the issue?
Per the socket.io docs, these are two server-side initialization sequences that should work:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
or
var app = require('express').createServer();
var io = require('socket.io')(app);
app.listen(80);
You don't have either of these.
Related
I'm using req.session.userID variable to set a sessionID for the user.
My code is
On the server side,
router.post('/signin', bodyParser.json(),function(req, res){
var db = req.db;
var collection = db.get('userCollection');
var name = req.body.name;
var password = req.body.password;
name = name.trim();
password = password.trim();
collection.find({"name":name}, {}, function(e1, username){
if (e1 === null){
if (username[0].password == password) {
req.session.userID = username[0]._id;
var string2 = "before session" + req.session.userID + "after session" + username[0]._id;
res.send(string2);
}
else {
res.send("Failure!");
}
}
});
And on the client side
router.post('/signin', bodyParser.json(),function(req, res){
var db = req.db;
var collection = db.get('userCollection');
var name = req.body.name;
var password = req.body.password;
name = name.trim();
password = password.trim();
collection.find({"name":name}, {}, function(e1, username){
if (e1 === null){
if (username[0].password == password) {
req.session.userID = username[0]._id;
var string2 = "before session" + req.session.userID + "after session" + username[0]._id;
res.send(string2);
}
else {
res.send("Failure!");
}
}
});
I have also set a secret token for in my app.js as advised in some other answers, but still whenever I user req.session.userID it gives me an error.
The moment I remove req.session.userID and just send a normal statement back it works. Can anyone tell me what could be the possible reason for this.
My app.js looks something like this...
var session = require('express-session');
app.use(session({
secret: 'secret token'
}))
I have even installed express-session. Should I be doing something else too?
Full app.js code,
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/learnproject1');
var logger = require('morgan');
var bodyParser = require('body-parser');
var indexRouter = require('./routes/myroutes.js');
//var userRouter = require('.')
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(function(req,res,next){
req.db = db;
next();
});
app.use('/', indexRouter);
//app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
app.use(session({
secret: 'secret token'
}))
// 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;
I have a nodejs app running on Heroku. Here is the server.js file
var express = require('express')
, cors = require('cors')
, app = express();
var http = require('http').Server(app);
var io = require("socket.io").listen(http);
app.use(cors());
require('./modules/routes.js')(app,io);
app.set('port', process.env.PORT || 5000);
app.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
Here is my routes.js
"use strict";
const bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var time = require('express-timestamp');
var Promise = require('promise');
var momentjs = require('moment');
var _ = require('lodash');
var method = routes.prototype;
function routes(app, io) {
app.use(time.init);
app.use(cookieParser());
app.use(session({ secret: 'asdo8rter65edfgfd53wet34634632y4bluaq', resave: true, saveUninitialized: true }));
app.all('/', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.use(bodyParser.json());
app.post('/testHeroku', function(req, res) {
console.log(req);
res.write(JSON.stringify({
process: "success"
}));
res.end();
});
}
method.getroutes = function() {
return this;
}
module.exports = routes;
I'm trying to access /testHeroku from an ionic app running in android emulator.
Ionic code:
vm.testHeroku = function(){
console.log('testing heroku');
var testdata = {
url: config.baseURL + 'testHeroku',
dataServer: {
serverTaskRequest: 'getUADSF'
}
}
runajax.runajax_function(testdata, function (testdataResponse) {
if (testdataResponse.process == 'success') {
alert(testdataResponse.process);
}
});
};
Here goes my config.baseURL = abcd-1234.herokuapp.com (This is example for the heroku app url)
I don't receive any return form the http call.
Code for run_ajax service
.service('runajax', ['$http', function ($http) {
this.runajax_function = function (request, callback) {
var url = request.url;
var dataServer = request.dataServer;
// console.log('runajax function called -> ' + url);
// console.log(dataServer);
$http.post(url, dataServer).success(function (data, status, headers, config) {
callback(data);
})
.error(function () {
callback(status);
});
}
}])
I got it working. There was an error with app.set('port', process.env.PORT || 5000); I changed it to var port = process.env.PORT || 8080;
While starting nodejs with express application on AWS ubuntu using pm2, logs shows below error.
Below is my app.js file
// Packages
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 app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
//app.locals.basedir = path.join(__dirname, 'views');
global.__base = __dirname + '/';
var dbhelper = require('./routes/dbhelper.js');
var common = require('./routes/common.js');
var ErrorHandler = require('./routes/errorhandler.js');
var authenticationRepository = require(__base + 'repository/authentication.js');
// set up mustbe config
var mustBe = require("mustbe");
var mustBeConfig = require("./mustBeConfig");
mustBe.configure(mustBeConfig);
// Routes
var routes = require('./routes/index');
// Make database connection available to router
app.use(function (req, res, next) {
common.ActionOutput.Message = '';
common.ActionOutput.Results = [];
req.ActionOutput = common.ActionOutput;
req.ActionStatus = common.ActionStatus;
req.ApplicationCookies = common.ApplicationCookies;
req.Security = common.Security;
req.Constants = common.Constants;
console.log(req.url);
// Temp Keys
var key = common.Encrption('firstword|secondword');
var dkey = common.Decryption('3TYkoj9CgZZU+IdD+PAqC3U9xlyJuG40g2fXAJn3GB8=');
var key = req.get('Key');
var msg = null;
if (key == undefined || key == null || key == '')
msg = 'header key not found.';
else {
try {
var keys = common.Decryption(key).split('|');
if (keys.length < 2 || keys.length > 3)
msg = 'header key is incorrect.';
else
next();
} catch (err) {
msg = 'Unable to decrypt header value.';
}
}
if (msg != null) {
common.ActionOutput.Message = msg;
common.ActionOutput.Status = common.ActionStatus.Error;
return res.send(JSON.stringify(common.ActionOutput));
}
});
app.use('/', routes);
app.use(function (err, req, res, next) {
if (!err)
return next();
ErrorHandler.SaveErrorLog(req, res, null, err.message, err.stack, req.connection.remoteAddress, err.path);
});
// catch 404 and forward to error handler
app.use(function (req, res, next) {
console.log('Exception: Not Found ' + req.url);
var APIKey = req.get('Key');
var UserKey = req.get('UserKey');
var DeviceToken = req.get('DeviceToken');
ErrorHandler.SaveErrorLog(req, res, UserKey, 'Resource not found!!!', '', req.connection.remoteAddress, req.url);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('shared/error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
var APIKey = req.get('Key');
var UserKey = req.get('UserKey');
var DeviceToken = req.get('DeviceToken');
ErrorHandler.SaveErrorLog(req, res, UserKey, 'Resource not found!!!', '', req.connection.remoteAddress, req.url);
});
process.on('uncaughtException', function (err, abc) {
console.log('uncaughtException: ' + err);
ErrorHandler.SaveErrorLog(null, null, null, 'UnCaught exception: ' + err.message, err.stack, 'IP', err.address);
});
module.exports = app;
app.listen(3000, function () {
console.log('Server starts on port: ' + 3000);
});
netstat says below which seems to be a problem to access it from outside. Application is running after changing port but not accessible.
Please suggest.
I am using webstorm and I have installed the body-parser module but bodyParser.json and bodyParser.urlencoded still gives a unresolved method error.
var express = require('express');
var connect = require('connect');
var logger = require('morgan');
var bodyParser = require('body-parser');
var app = express();
port = process.env.PORT || 8080;
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
require('./routes.js')(app);
app.listen(port);
console.log('The App runs on port ' + port);
routes
var requests = require('config/requests');
var request = require('request');
module.exports = function(app) {
app.get('/', function(req, res) {
res.end("Node-Android-Chat-Project");
});
app.post('/login',function(req,res){
var name = req.body.name;
var mobno = req.body.mobno;
var reg_id = req.body.reg_id;
requests.login(name,mobno,reg_id,function (found) {
console.log(found);
res.json(found);
});
});
app.post('/send',function(req,res){
var fromu = req.body.from;
var fromn = req.body.fromn;
var to = req.body.to;
var msg = req.body.msg;
requests.send(fromn,fromu,to,msg,function (found) {
console.log(found);
res.json(found);
});
});
app.post('/getuser',function(req,res){
var mobno = req.body.mobno;
requests.getuser(mobno,function (found) {
console.log(found);
res.json(found);
});
});
app.post('/logout',function(req,res){
var mobno = req.body.mobno;
requests.removeuser(mobno,function (found) {
console.log(found);
res.json(found);
});
});
};
Trying installing the body-parser module again.
Use npm install body-parser --save
I am making a chat for customers of a web page, with express.js, and socket.io, and I'm trying to manage sessions with express-session, my problem is, how do I read the session values on the socket.
Here's part of my code.
Thanks for the help :)
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var bodyParser = require('body-parser');
var session = require('express-session');
var shortid = require('shortid');
app.use(express.static('public'));
app.use( session({
secret: 'dont move',
resave: true,
saveUninitialized: true
})
);
app.use( bodyParser.urlencoded({ extended: true }) );
app.post('/chat', function(req, res){
var sess = req.session;
sess.ssid = shortid.generate();
res.render('chat', { name: "name" });
});
io.on('connection', function(socket){
socket.on('chat message', function( data ){
if( data.msg.trim() != '' ){
console.log('message: ' + data.msg);
//Here I want to read the ssid session var, so I can manage many chats at the same time
}
});
socket.on('disconnect', function(){
console.log('Hey, someone disconected!');
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
You can configure socket authorization
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var bodyParser = require('body-parser');
var session = require('express-session');
var shortid = require('shortid');
app.use(express.static('public'));
app.use( session({
secret: 'dont move',
resave: true,
saveUninitialized: true
})
);
app.use( bodyParser.urlencoded({ extended: true }) );
app.post('/chat', function(req, res){
var sess = req.session;
sess.ssid = shortid.generate();
res.render('chat', { name: "name" });
});
var util = require('util';
var connect = require('connect');
var parseSignedCookie = connect.utils.parseSignedCookie;
io.configure(function () {
io.set('authorization', function (data, callback) {
if(data.headers.cookie) {
data.cookie = cookie.parse(data.headers.cookie);
data.sessionId = parseSignedCookie(data.cookie['ssid'], 'dont move');
}
callback(null, true);
});
io.on('connection', function(socket) {
var sessionId = socket.handshake.sessionId;
socket.on('chat message', function( data ){
if( data.msg.trim() != '' ){
console.log('message: ' + data.msg);
// NOW YOU CAN USE `sessionId`
}
});
socket.on('disconnect', function(){
console.log('Hey, someone disconected!');
});
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});