socket io .use() is not a function - javascript

Im trying to use sessions middleware to connect express and socket.io
However i get this error:
io.use(function(socket, next){
^
TypeError: io.use is not a function
at Object.<anonymous> (/home/ubuntu/workspace/newserver.js:30:4)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:990:3
Here is my code:
var http = require('http');
var path = require('path');
var async = require('async');
var express = require('express');
var socketio = require('socket.io');
var sessions = require('express-session');
var mysql = require('mysql');
var RedisStore = require('connect-redis')(sessions);
var bodyParser = require('body-parser');
// App declaration
var router = express();
var server = http.createServer(router);
var io = socketio.listen(server);
io.set('log level',0);
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({extended:true}));
var sessionMiddleware = sessions({
store: new RedisStore({}),
secret: '901uj0394-0i4-#',
resave:true,
saveUninitialized:true
});
router.use(sessionMiddleware);
var session;
var appConfig = {
title: 'The Warring States 2'
};
router.set('views', path.resolve(__dirname,'client/views'));
router.set('view engine', 'pug');
var connection = mysql.createConnection({
// SQL Information
host: 'localhost',
user: 'boyton',
password: '',
database: 'WarringStates'
});
connection.connect(function(error){
// callback
if(!!error) {
console.log('Error!');
console.log(error);
}
else {
console.log('Connected to the database');
}
});
// Socket
var sockets = [];
var gamelobbies = [];
Im only starting out with node and expresss, I created a c9 container for node and installed the default Packages to work with the stack, Ive "tried" to update node and npm and express as well. However im not sure if they're up to the latest versions
here is what i get when i invoke check-node-versions
node: 4.7.3
npm: 2.15.11
yarn: not installed
express version 3.6.2
any help and input would be great. Thanks guys.

Change this line:
var io = socketio.listen(server);
to this:
// create an instance of socket.io, bound to our web werver
var io = socketio(server);
And, then make sure you have this somewhere:
// start the web server
server.listen(80);
The socketio library is a constructor and it wants you to call it and pass it the server to create the io object (an instance of the socket.io server). You then separately start the server so it can be used for both your http requests and your socket.io requests.
The way you were doing it, socketio was not the right kind of object to call .listen() on. It was the module handle rather than an instance and thus io was the wrong kind of object and thus why there was no .use() method.

Related

Deploying Express app to Vercel gives errors

Running the server locally produces no problems, however when I deploy to Vercel I get the following error:
TypeError: Cannot read properties of undefined (reading 'startsWith') at connectionStringHasValidScheme (/var/task/server/node_modules/mongodb-connection-string-url/lib/index.js:9:30) at new ConnectionString (/var/task/server/node_modules/mongodb-connection-string-url/lib/index.js:85:34) at parseOptions (/var/task/server/node_modules/mongodb/lib/connection_string.js:201:17) at new MongoClient (/var/task/server/node_modules/mongodb/lib/mongo_client.js:46:63) at Object.<anonymous> (/var/task/server/db/conn.js:3:16) at Module._compile (node:internal/modules/cjs/loader:1159:14) at Module._extensions..js (node:internal/modules/cjs/loader:1213:10) at Module.load (node:internal/modules/cjs/loader:1037:32) at Module._load (node:internal/modules/cjs/loader:878:12) at Module.require (node:internal/modules/cjs/loader:1061:19)
I'm really not sure what the problem is - I've done a bit of googling but it hasn't produced many results for this issue (at least not that I found).
server.js
const express = require("express");
const app = express();
const cors = require("cors");
const bp = require('body-parser');
require("dotenv").config({ path: "./db/config.env" });
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
app.use(require("./routes/auth"));
app.use(require("./routes/user"));
const dbo = require("./db/conn");
app.listen(port, () => {
dbo.connectToServer(function (err) {
if (err) console.error(err);
});
console.log(`Server is running on port: ${port}`);
});
conn.js
const { MongoClient } = require("mongodb");
const Db = process.env.ATLAS_URI;
const client = new MongoClient(Db, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
var _db;
module.exports = {
connectToServer: function (callback) {
client.connect(function (err, db) {
// Verify we got a good "db" object
if (db)
{
_db = db.db("preview");
console.log("Successfully connected to MongoDB.");
}
return callback(err);
});
},
getDb: function () {
return _db;
},
};
I tried cutting the code down to a minimal just to figure out what component is causing the bug, unfortunately with no result.
When you deploy your app to Vercel, you also need declare your environment variables in your project settings page.
Go to the Environment Variables page of your Project Settings and define ATLAS_URI value. Note that you need to deploy your project again before new environment variables becomes available.

Node JS app shuts down after ten seconds in Production env but runs fine on local env

I have a Node JS app which serves as a backend for a React web app. The application when started serves the React app and handles all the API calls. I connect to a MySQL database for data fetch. The app runs normally on local environment but crashes when deployed on an Ubuntu server(on AWS). On server, the app starts normally but after few seconds it crashes.
This is the error it throws when started
Error connecting: Error: connect ETIMEDOUT
at PoolConnection.Connection._handleConnectTimeout (/home/ubuntu/localSystem/node_modules/mysql/lib/Connection.js:412:13)
at Object.onceWrapper (events.js:313:30)
at emitNone (events.js:106:13)
at Socket.emit (events.js:208:7)
at Socket._onTimeout (net.js:422:8)
at ontimeout (timers.js:498:11)
at tryOnTimeout (timers.js:323:5)
at Timer.listOnTimeout (timers.js:290:5)
--------------------
at Protocol._enqueue (/home/ubuntu/localSystem/node_modules/mysql/lib/protocol/Protocol.js:144:48)
at Protocol.handshake (/home/ubuntu/localSystem/node_modules/mysql/lib/protocol/Protocol.js:51:23)
at PoolConnection.connect (/home/ubuntu/localSystem/node_modules/mysql/lib/Connection.js:119:18)
at Pool.getConnection (/home/ubuntu/localSystem/node_modules/mysql/lib/Pool.js:48:16)
at Object.<anonymous> (/home/ubuntu/localSystem/model/db.js:29:12)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
DB connection file (db.js):
var connection = mysql.createPool({
connectionLimit: 100,
host : 'xxxx',
port : xxxx,
user : 'username',
password : 'password',
database : 'myDB'
});
connection.getConnection(function(err) {
if (err) {
console.log('Error connecting: ' + err.stack)
return;
}
console.log('Connected as id ' + connection.threadId)
});
module.exports = connection;
Server.js
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
app = express();
var appRoutes = require('./routes/appRoutes');
app.use(express.static(path.join(__dirname, './client/build')));
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', appRoutes);
module.exports = app;
index.js
var app = require('./server');
//const { connection } = require('./database');
var port = 5001;
app.set('port', port);
app.listen(app.get('port'), () => {
console.log(`server on port ${app.get('port')}`);
});
AppModel.js
var sql = require('./db.js');
//Task object constructor
var Task = function(task){
this.task = task.task;
this.status = task.status;
this.created_at = new Date();
};
Task.getAllCustomerStatusRecords = function getAllCustomerStatusRecords(result) {
sql.query("Select a, b, c, call_provider_id from myTable order by id desc limit 20", function (err, res) {
if(err) {
console.log("error: ", err);
result(null, err);
}
else {
console.log('Customer status records : ', res);
result(null, res);
}
});
sql.releaseConnection()
};
I have a similar set up for another Node app but without mysql and it runs without issues.I'm not sure why it crashes in this case.
EDIT:
The API request does make a DB call. However that is only when the user explicitly selects some options and then makes a fetch call on the webpage. Initially though, there are no outwards API calls either to Db or external services.

Socket io implementation, Getting TypeError('"listener" argument must be a function')

I am trying to implement Socket IO with my angular Js project. I am new into this, please help.
This is my server.js file
var express = require('express');
var path = require('path');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var port = 8080;
app.use(express.static(path.join(__dirname, "app")));
io.on('connection'), function(socket){
console.log('new connection made');
}
server.listen(port, function(){
console.log('Listening to port '+ port);
})
I have copied the socket.io.js file from socket.io-client and put it in my lib folder. So my index.html has
<script src="lib/js/socket.io.js"></script>
//all other includes required
<body>
//code here
</body>
heres is the error I get to see when I execute nodemon server.js
[nodemon] starting `node server.js`
events.js:216
throw new TypeError('"listener" argument must be a function');
^
TypeError: "listener" argument must be a function
at _addListener (events.js:216:11)
at Namespace.addListener (events.js:275:10)
at Server.(anonymous function) [as on]
(D:\SocketIOExperiment\ProjExperiment\node_modules\socket.io\lib\index
.js:456:29)
at Object.<anonymous>
(D:\SocketIOProject\SmartAdminExperiment\server.js:11:4)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
[nodemon] app crashed - waiting for file changes before starting...
Small typo on your code.Try this :
var express = require('express');
var path = require('path');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var port = 8080;
app.use(express.static(path.join(__dirname, "app")));
io.on(('connection'), function(socket){
console.log('new connection made');
})
server.listen(port, function(){
console.log('Listening to port '+ port);
})
Remember, io.on(event,cb) is a function call that registers the cb function to the event.

how to use connect-orientdb module with express

My goal is to connect my server code that its with nodejs and expressjs framework to my database that is with orientdb.
first of all i wanted to store my sessions in database. but i had difficulty connecting my server to database.
the error that i get when i execute server.js:
/Users/soroush/Desktop/nodeOrient/node_modules/connect-orientdb/lib/connect-orientdb.coffee:191
})(connect.session.Store);
^
TypeError: Cannot read property 'Store' of undefined
at module.exports (/Users/soroush/Desktop/nodeOrient/node_modules/connect-orientdb/lib/connect-orientdb.coffee:22:46)
at Object.<anonymous> (/Users/soroush/Desktop/nodeOrient/server.js:8:48)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Function.Module.runMain (module.js:575:10)
at startup (node.js:160:18)
at node.js:449:3
and my server.js code is:
var express = require('express'),
cs = require("coffee-script/register"),
app = express(),
path = require('path'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
config = require('./config/config.js'),
orientDBStore = require('connect-orientdb')(session),
OrientDB = require('orientjs'),
orientDBConfig = {
server : {
host: "localhost",
port:2424
},
db : {
user_name: "admin",
user_password: "admin"
},
database : "sessions",
class_name : "sessions_class"
},
server = OrientDB({
hose : "localhost",
port : "2424",
username : "root",
password : "root"
})
;
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('hogan-express'));
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname,'public' )));
app.use(cookieParser());
require('./routes/route.js')(express, app);
app.use(session({
secret:"mySecret",
store: new orientDBStore(orientDBConfig)
}));
app.listen(8000, function () {
console.log("app is listening on port 8000");
})
my main problem is that the connect-orientdb was used when the session module was builtin in express, but now that session is a different module i have occurred to this problem.
Check out this guide for ExpressJS in OrientDB: Blog Tutorial with ExpressJS and OrientDB.
And try to use:
orientDBStore = require('orient')(session),
instead of:
orientDBStore = require('connect-orientdb')(session),
Finally i found a solution for it if anyone faced this problem:
var session = require('express-session'),
OrientoStore = require('connect-oriento')(session);
app.use(session({
secret: 'SomeSecret',
store: new OrientoStore({
server: "host=localhost&port=2424&username=dev&password=dev&db=test"
})
}));
for more info this github link is useful.

Sharing socket.io to other modules gives empty object

I am trying to share socket.io's socket object in different node.js modules although I fail and get empty object with
Cannot call method 'on' of undefined
My code :
app.js
var express = require('express')
, app = express();
var server = require('http').createServer(app)
, io = require('socket.io').listen(server)
var routes = require('./routes')
, path = require('path')
, rss = require('./routes/rss')
// ...
exports.io = io;
routes/rss.js
io = require(__dirname + '/../app');
console.log(io);
io.sockets.on('connection', function(
console.log("Connection on socket.io on socket");
// .. do stuff
});
That's the output I get from this :
$ node app.js
info - socket.io started
{}
/home/XXX/programming/nodejs/node-express-aws/routes/rss.js:10
io.sockets.on('connection', function(socket){
^
TypeError: Cannot call method 'on' of undefined
at Object.<anonymous> (/home/XXX/programming/nodejs/node-express-aws/routes/rss.js:10:12)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/home/XXX/programming/nodejs/node-express-aws/app.js:9:10)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
Although I have tried and I can do the same with socket.io only in one (app.js) file
var express = require('express')
, app = express();
var server = require('http').createServer(app)
, io = require('socket.io').listen(server)
var routes = require('./routes')
, path = require('path')
, rss = require('./routes/rss')
// ...
io.sockets.on('connection', function(socket){
logger.debug("Connection on socket.io on socket");
socket.emit('news', {will: 'be recived'});
});
Since, in app.js, you have:
exports.io = io;
then you would need to use it like so:
var app = require('../app');
var io = app.io;
That is you say, you attached a property called io to the module, so when you require that module, you get an object that has the io property set.
You could also do
module.exports = io;
and then leave rss.js as you have it now.
All that said, if you're running app.js with Node, you'll much more commonly see the io object injected into other modules (instead of the other way around); for example:
app.js
var express = require('express')
, app = express();
var server = require('http').createServer(app)
, io = require('socket.io').listen(server)
var routes = require('./routes')
, path = require('path')
, rss = require('./routes/rss')
// ...
rss(io); // pass `io` into the `routes` module,
// which we define later to be a function
// that accepts a Socket.IO object
routes/rss.js
module.exports = function(io) {
io.sockets.on('connection', function(
console.log("Connection on socket.io on socket");
// .. do stuff
});
}
I pass the io object into the connection handler.
var socket = require('./routes/socket.js');
io.sockets.on('connection', function(sock){
socket.stuff(sock, io);
});
./routes/socket.js should contain the following:
var socket = module.exports = {};
socket.stuff = function(sock, io){
//handle all events here
};

Categories

Resources