Node.js application crashing - javascript

I am just beginning with node.js and was trying to deploy Pusher's example authentication code but it fails
Here is the code -
var express = require( 'express' );
var Pusher = require( 'pusher' );
var app = express( express.logger() );
app.use( express.bodyParser() );
var pusher = new Pusher( { appId: '<appid>', key:'<key>', secret:'<secret>' } );
app.post( '/pusher/auth', function( req, res ) {
var socketId = req.body.socket_id;
var channel = req.body.channel_name;
var auth = pusher.auth( socketId, channel );
res.send( auth );
} );
var port = process.env.PORT || 5000;
app.listen( port );
Executing node messaging-server.js throws the following -
user#ubuntu:~/Desktop/messaging_server$ node messaging-server.js
Error: Most middleware (like logger) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.
at Function.Object.defineProperty.get (~/Desktop/messaging_server/node_modules/express/lib/express.js:89:13)
at Object.<anonymous> (~/Desktop/messaging_server/messaging-server.js:11:28)
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 Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
How do I debug this?

You have express 4 installed, but Pusher's docs are using an older version of express. Let's use morgan to replace the now-defunct express.logger():
var express = require( 'express' );
var Pusher = require( 'pusher' );
var logger = require('morgan');
var app = express( logger() );
app.use( express.bodyParser() );
var pusher = new Pusher( { appId: '<appid>', key:'<key>', secret:'<secret>' } );
app.post( '/pusher/auth', function( req, res ) {
var socketId = req.body.socket_id;
var channel = req.body.channel_name;
var auth = pusher.auth( socketId, channel );
res.send( auth );
} );
var port = process.env.PORT || 5000;
app.listen( port );
(Don't forget to run npm install morgan)

Related

Express JS REST API with MySQL

I am doing an exercise with Express.js and MySQL. At the moment I have 4 files. The error is,
TypeError: areas.getAreas is not a function
at Object.<anonymous> (/--/--/--/src/routes/userRoutes.js:4:13)
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)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/--/--/--/src/app.js:10:20)
at Module._compile (module.js:653:30)
But I am sure I am declaring the variable and function so, I don't understand why is it happening.
I tried to get the value of the variable areas in the userRoutes.js file but console just show me an "{}". I also tried to change the sintaxis of the function of the areas.js file, writing it as function and not like an object.
The main file is, app.js and it contains:
const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const connection = require('/--/--/--/db/connection.js');
const userRoutes = require('/--/--/--/routes/userRoutes.js');
app.set('port', process.env.PORT || 3000);
app.use(morgan('dev'));
app.use(bodyParser.json());
connection(mysql);
userRoutes(app);
app.listen(app.get('port'), ()=> {
console.log('server on port 3000');
});
The next files are:
connection.js
'use strict';
module.exports = function connection(mysql){
mysql.createConnection({
host: 'http://x.x.x.x',
user: 'xxxxxxx',
password: 'xxxxxxx',
database: 'xxxxxxx'
})
};
areas.js
'use strict';
let areasModel = {};
areasModel.getAreas = (callback) => {
if(connection) {
connection.query(
"SELECT * FROM areas",
(err, rows) => {
if(err) {
throw err;
}
else {
callback(null, rows);
}
}
);
}
};
module.exports = areasModel;
userRoutes.js
'use strict';
const areas = require('../models/areas');
module.exports = function (app) {
app.get("/", (req,res)=>{
areas.getAreas((err, data) => {
res.json([]);
});
});
}
try importing connection.js in areas.js,
maybe because never enter in that if statement, returns undefined

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.

socket io .use() is not a function

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.

Node.js file server on Rpi3 Jesse

I have a file server that works perfectly on my Rpi 2 with Raspian and I have been trying to migrate it to a newer Rpi3 with Jesse. Every time I try to run it I get the following error stack
/media/pi/DemoServer.js:82
server.listen(port, () => {
^
SyntaxError: Unexpected token )
at Module._compile (module.js:439:25)
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 Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
Any suggestions on why this is occurring? Is there a subtle nuance between the two distributions that I should address?
Here is the code for the server (with some omissions).
const express = require('express');
const formidable = require('formidable');
const fs = require('fs-extra');
const http = require('http');
const util = require('util');
const serveIndex = require('serve-index');
const serveStatic = require('serve-static');
const path = require('path');
const server = express();
const port = process.env.PORT || 1001;
const dirToServe = '/media/pi/Shared';
function setHeaders(res, filepath) {
res.setHeader('Content-Disposition', 'attachment; filename=' + path.basename(filepath));
}
server.post('/media/pi/Shared', function(req,res) {
});
//Serve the static folder and the index of the folder
server.use('/', serveIndex(dirToServe, { icond: true }));
server.use('/', serveStatic(dirToServe, {setHeaders: setHeaders }));
server.listen(port, () => {
console.log('listening on port ' + port);
});

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