Simple NodeJS socketIO server throws error - node.js

Trying to debug this simple NodeJS socketIO server.
I keep getting the following error message on launch. I can't see anything wrong with the code.
Can anyone help?
TypeError: listener must be a function
at TypeError ()
at Namespace.EventEmitter.addListener (events.js:130:11)
at Server.(anonymous function) [as on] (/Users/foo/bin/node_modules/socket.io/lib/index.js:364:16)
at Object. (/Users/foo/bin/foo.js:11:4)
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)*
var app = require("express");
var server = require("http").Server(app);
var io = require("socket.io")(server);
io.on("connection", handleClient);
var handleClient = function (socket) {
// we've got a client connection
socket.emit("tweet", {user: "nodesource", text: "Hello, world!"});
};
app.listen(8080);

You're missing some parens:
var app = require('express')();

you have forgotten to take an instance of express. I hope my below example will help you.
var express = require("express");
var app = express();
var server = require("http").Server(app);
var io = require("socket.io")(server);
io.on("connection", handleClient);
var handleClient = function (socket) {
// we've got a client connection
socket.emit("tweet", {user: "nodesource", text: "Hello, world!"});
};
app.listen(8080);

Related

module.export = mongoose.model('User', new Scheme({ ReferenceError: Scheme is not defined - nodejs issue

I'm new to node.js. I was trying to run the code from the link https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens. When I tried to run the server.js. The following error was coming:
E:\Eclipse IDE\Enide-Studio-2014.17-luna-SR1-win64-20141011\Enide-Studio-2014.17-luna-SR1-win64\ws\node-token-jwt\app\models\user.js:7
module.export = mongoose.model('User', new Scheme({
^
ReferenceError: Scheme is not defined
at Object.<anonymous> (E:\Eclipse IDE\Enide-Studio-2014.17-luna-SR1-win64-20141011\Enide-Studio-2014.17-luna-SR1-win64\ws\node-token-jwt\app\models\user.js:7:44)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (E:\Eclipse IDE\Enide-Studio-2014.17-luna-SR1-win64-20141011\Enide-Studio-2014.17-luna-SR1-win64\ws\node-token-jwt\server.js:12:14)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
Please help me !
Also see attached of project structure.
server.js
// =======================
// get the packages we need ============
// =======================
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var config = require('./config'); // get our config file
var User = require('./app/models/user'); // get our mongoose model
// =======================
// configuration =========
// =======================
var port = process.env.PORT || 8080; // used to create, sign, and verify tokens
mongoose.connect(config.database); // connect to database
app.set('superSecret', config.secret); // secret variable
// use body parser so we can get info from POST and/or URL parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// use morgan to log requests to the console
app.use(morgan('dev'));
// =======================
// routes ================
// =======================
// basic route
app.get('/', function(req, res) {
res.send('Hello! The API is at http://localhost:' + port + '/api');
});
// API ROUTES -------------------
// we'll get to these in a second
// =======================
// start the server ======
// =======================
app.listen(port);
console.log('Magic happens at http://localhost:' + port);
user.js
// get an instance of mongoose and mongoose.Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//set up a mongoose model and pass it using module.exports
module.export = mongoose.model('User', new Scheme({
name : String,
password : String,
admin : Boolean
}));
EDIT-1: I can see the new issue now:
C:\Users\workspace-nod\node-token-jwt\node_modules\mongodb\lib\server.js:242
process.nextTick(function() { throw err; })
^
Error: getaddrinfo ENOTFOUND noder noder:27017
at errnoException (dns.js:27:10)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:78:26)
Please guide on this.

Object function createServer() has no method 'bodyparser'

I am new to nodeJS. I am trying to use different middlewares with connect middleware.
this is my code:
var connect = require('connect');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var app = connect()
.use(connect.bodyParser())
.use(connect.cookieParser('tobi is a cool ferret'))
.use(function(req, res){
console.log(req.cookies);
console.log(req.signedCookies);
res.end('hello\n');
}).listen(3000);
I have installed every middleware through npm.
I am getting this error while running this file.
/home/dipesh/Desktop/temp/temp.js:5
.use(connect.bodyParser())
^
TypeError: Object function createServer() {
function app(req, res, next){ app.handle(req, res, next); }
merge(app, proto);
merge(app, EventEmitter.prototype);
app.route = '/';
app.stack = [];
return app;
} has no method 'bodyParser'
at Object.<anonymous> (/home/dipesh/Desktop/temp/temp.js:5:14)
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:929:3
Any suggestions?
.use(bodyParser())
not
.use(connect.bodyParser())
You have required body-parser, but then never used it.
You are essentially doing
var a = function(){};
var b = {};
b.a();
which is not correct because b has not 'a' property.

How to configure ssl on express

I am trying to configure ssl in express with the following configuration but I keep on getting errors and I am not able to figure out how to solve this.
use strict';
//dependencies
var config = require('./config'),
//uuid = require('node-uuid'),
express = require('express'),
session = require('express-session'),
mongoStore = require('connect-mongo')(session),
http = require('http'),
path = require('path'),
passport = require('passport'),
mongoose = require('mongoose'),
helmet = require('helmet'),
https = require('https');
//create express app
var app = express();
//keep reference to config
app.config = config;
app.server = https.createServer(app.config.ssl_options, app);
//listen u
app.server.listen(443);
Here is how I am importing the config files, the config files are placed in config.js
exports.ssl_options = {
key: fs.readFileSync('./ssl.key'),
cert: fs.readFileSync('./2b62bb384fb2b9.crt'),
ca: fs.readFileSync('./gd_bundle-g2-g1.crt')
};
Here are my errors
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EACCES
at errnoException (net.js:904:11)
at Server._listen2 (net.js:1023:19)
at listen (net.js:1064:10)
at Server.listen (net.js:1138:5)
at Object.<anonymous> (/home/kseguy/node_projects/prwrite/app.js:100: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 Function.Module.runMain (module.js:497:10)
The line that I am getting the errors is
//listen u
app.server.listen(443);
If you're binding to a port < 1024, you have to use sudo to start your server because only privileged users (root) can bind to those ports.

Node.js error no server startup

As a part of angular.js course, i downloaded and installed node.js, inserted server.js file in main folder with following content :
var connect = require('connect');
connect.createServer(
connect.static("../angularjs")
).listen(5000);
and then tried to run server by cli, but im getting error in cli:
TypeError: Object function createServer() {
function app(req, res, next){ app.handle(req, res, next); }
merge(app, proto);
merge(app, EventEmitter.prototype);
app.route = '/';
app.stack = [];
return app;
} has no method 'static'
at Object.<anonymous> (C:\Program Files (x86)\nodejs\server.js:4:19)
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
try:
var connect = require('connect');
var serveStatic = require('serve-static');
var app = connect();
app.use(serveStatic('angularjs'));
app.listen(5000);
Should work for you!
EDIT:
With Connect 3.0 .static() is moved to a separate package called serve-static.
So you'll have to install that before running this code.
Edit: THis is for an older version of Node and therefore doesn't answer the question. See the comments below.
To use connect, you need to setup the environment, and then create the server
var connect = require('connect');
car app = connect();
app.static("../angularjs");
connect.createServer(app).listen(5000);
You may also be able to do it the brief way that you have by:
connect.createServer(
connect().static("../angularjs")
).listen(5000);

Socket.io and express setup

I' m trying socket.io Cut and pasting the exact code they provide I have an error ! Any ideas I'm running on windows8 and node v0.10.26 ?
var io = require('socket.io')(server);
^
TypeError: object is not a function
at Object.<anonymous> (c:\Users\david wilson\TravelShopOffers\app_socketio:3:30)
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:902:3
Here's the code from their site :
In conjunction with Express
Starting with 3.0, express applications have become request handler functions that you pass to http or http Server instances. You need to pass the Server to socket.io, and not the express application function.
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
io.on('connection', function(){ /* … */ });
server.listen(3000);
Will not be the best answer, as I was just discovering and experimenting on express/socket.io a few days ago.
Anyway I came up with the following ( interested in feedback ) :
var app = require('express')();
var server = app.listen(3000);
var io = require('socket.io').listen(server);
io.sockets.on('connection', function(socket)
{
socket.on('myEvent',function(){ /* … */ });
}
);
Hope this will help

Resources