Why can not my client get socket.io.js? - node.js

I am learning to use socket.io, but when I add
script(type='text/javascript', src='/socket.io/socket.io.js')
in my client, and I add code:
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
console.log('------------connection');
});
in app.js, but my client do get 404 error when trying to get /socket.io/socket.io.js.
I chage my code to :
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 routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
var server = require('http').createServer();
var io = require('socket.io').listen(server);
// 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(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
var userlist = {};
io.on('connection', function(data){
console.log('------------connection');
socket.name = data.user;
if (!userlist[data.user]) {
userlist[data.user] = data.user;
};
io.emit("online", { userlist: userlist, user: data.user});
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
module.exports = app;
and I also have the code as follow in my javascript:
$(document).ready(function() {
var socket = io.connect('http://localhost:3000');
// other code
}

Related

Socet.io not working in routes

I have searched all over but all I find are basic ways to use socket.io.
I am trying to use socket.io in one of my routes but cant. I am using express, node.js, and jade. My issues is that i cant access io variable form app.j in other routes. Im not sure if am just supposed to call it every time. Also, when i try to requre the exported app.js modules its says that the app.j could not be found.
app.js
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();
//SOCKET/I/o
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;
//
var login = require('./routes/login');
var index = require('./routes/index');
var users = require('./routes/users');
var news = require('./routes/news');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
// TODO Not sure if this is working
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', login);
app.use('/index',index);
app.use('/users', users);
app.use('/news',news);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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;
/routes/login.js
var express = require('express');
var app = require('./app');
var firebase = require("firebase");
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('login');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
module.exports = router;
/views/login.jade
doctype html
html
head
title login
link(rel='stylesheet', href='/stylesheets/main.css')
body
input(type="email",placeholder="email",id="userEmail")
input(type="password",placeholder="password",id="userPassword")
script(src="https://cdn.socket.io/socket.io-1.2.0.js")
script.
socket.on('connection', function (data) {
console.log(data);
socket.emit('my other event', {my: 'data'});
});
button(onclick='signin()') Sign In
button(onclick='signup()') Sign Up
As you're not running a single-page-app with html-router, the Socket.io instance is only initialised on the first route, so for every route you have to do this:
var socket = io()
socket.on('connection', function (data) {
console.log(data);
socket.emit('my other event', {my: 'data'});
});
Only then it would work.

node/express - exporting controller functionality

I am building a Node API on express which takes GET requests and uses the parameters supplied by the client to return the results of GET requests made to other API's.
In order to keep the controller thin when adding more API's I would like to export the logic within the controller into a separate .js file, and module.export those functions back in, to be used in the controller. The problem here is that the functions that are being exported do not appear to be visible within the controller.
Pasted below is before and after code to illustrate progress made so far.
app.js (before) - see router.get('/')
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 request = require('request');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
var router = express.Router();
if ( app.get('env') === 'development') {
var dotenv = require('dotenv');
dotenv.load();
};
var prodAdv = require('./lib/prod-adv.js')
// 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(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/api', router);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
router.get('/', function(req, res) {
request('https://openapi.etsy.com/v2/listings/active?includes=Images&keywords=' + req.param('SearchIndex') + '&limit=100&api_key=' + process.env.ETSY_KEY, function(error, response, body) {
res.header({'Access-Control-Allow-Origin': '*'});
var data = JSON.parse(body);
res.json(data);
});
});
router.use('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, accept, authorization");
next();
});
var server = app.listen(9876, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s',host,port);
});
module.exports = app;
This approach works, returning JSON objects. However the following approach to try and export the code does not work.
apiCaller.js
var express = require('express');
var app = express();
if ( app.get('env') === 'development' ) { var dotenv = require('dotenv'); dotenv.load(); };
var request = require('request');
var call, response;
var call = function(searchIndex) {
return request('https://openapi.etsy.com/v2/listings/active?includes=Images&keywords=' + searchIndex + '&limit=100&api_key=' + process.env.ETSY_KEY, function(error, response, body) {
response = JSON.parse(body);
});
};
module.exports.response = response;
module.exports.call = call;
app.js (after)
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 squid = require('./lib/apiCaller.js');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
var router = express.Router();
if ( app.get('env') === 'development') {
var dotenv = require('dotenv');
dotenv.load();
};
var prodAdv = require('./lib/prod-adv.js')
// 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(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/api', router);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
router.get('/', function(req, res) {
squid.call(req.param('SearchIndex'));
res.header({'Access-Control-Allow-Origin': '*'});
res.json(squid.response);
});
router.use('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, accept, authorization");
next();
});
var server = app.listen(9876, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s',host,port);
});
module.exports = app;
What occurs now in the browser is a 200 OK with an empty response body. console.logging the responses return undefined objects.
You need to rewrite your call function to have a callback since request(...) is asyncronous
var call = function(searchIndex, callback) {
request('https://openapi.etsy.com/v2/listings/active?includes=Images&keywords=' + searchIndex + '&limit=100&api_key=' + process.env.ETSY_KEY, function(error, response, body) {
if (!error && response.statusCode == 200) {
return callback(null, JSON.parse(body));
}
callback('error');
});
};
Only export call function, there's no need to export or even use response and no need for this line
var call, response;
Now you also need to use it a bit different way
router.get('/', function(req, res) {
res.header({'Access-Control-Allow-Origin': '*'});
squid.call(req.param('SearchIndex'), function(err, data){
if(!err) return res.json(data);
res.json({error: err});
});
});

NodeJS Express 4.9 and Socket.IO - 404 error on socket.io.js

I am trying to create an Express app with Socket.IO. It seems like Express has changed quite a lot and most of the code online about getting the 2 to work together is out of date. This is what I have:
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 routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io').listen(http);
io.on('connection', function(socket){
console.log('a user connected');
});
// 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(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
The server starts ok and says
info - socket.io started
However the front-end has a 404 error on http://example.com:3000/socket.io/socket.io.js
edit
If I add
http.listen(8080);
The server runs twice on port 3000 and 8080, the 3000 version does not load socket.io.js and the 8080 version does. How can I have it so the server is only running on 3000? changing it to 3000 errors and it tries to listen twice
The answer was to make the changes in bin/www.js instead of app.js
#!/usr/bin/env node
var debug = require('debug')('test1');
var app = require('../app');
app.set('port', process.env.PORT || 3000);
var http = require('http').Server(app);
var io = require('socket.io')(http);
var server = http.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
Change the io include to:
var io = require('socket.io')(http);
And towards the bottom add something like:
http.listen(3000, function() {
console.log('Listening on port %d', http.address().port);
});

GET /easyrtc/easyrtc.js 404 on express js 4

i have a 404 problem with EasyRTC on Express.js 4.
The console said : GET /easyrtc/easyrtc.js 404 4.500 ms - 1077
and here's my app.js code :
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 io = require('socket.io');
var easyrtc = require('easyrtc');
var routes = require('./routes/index');
var users = require('./routes/users');
var staticMiddleware = express.static(__dirname + "/public");
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// 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(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.get('/easyrtc/*', function (req,res) {
res.sendFile(__dirname + '/static');
})
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + server.address().port);
});
var webSockets = io.listen(server);
var rtc = easyrtc.listen(app, webSockets);
please help me, i've been searching for the solution all of this time and i couldnt find the solution at all. thanks before
NB : i'm generate express.js project from Terminal in linux , using command : express -e
Well, you may just to remove the code below:
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});

Socket.io Chat Application Refreshes When I Send a Message

I am trying to make a simple chat application using Node.js, socket.io, and express. However, if I click the send button in the main.jade file, the page refreshes, and no message appears. I also get this error in Firebug:
The connection to ws://127.0.0.1:3000/socket.io/?EIO=2&transport=websocket&sid=d_hNMPdXHed-j7LrAAAH was interrupted while the page was loading.
Main.jade
doctype html
html
head
meta(charset = "UTF-8")
script(src="/socket.io/socket.io.js")
script(src="http://code.jquery.com/jquery-1.11.1.js")
script.
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
body
ul#messages
form(action = "")
input#m(type = "text")
button Send
app.js
var express = require('express')
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var mongodb = require("mongodb");
var monk = require('monk');
var db = monk('localhost:27017/pesterchum');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(req,res,next){
req.db = db;
next();
});
app.use('/', routes);
app.use('/users', users);
/// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// 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('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
www
#!/usr/bin/env node
var debug = require('debug')('app');
var app = require('../app');
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
var io = require('socket.io').listen(server);
io.sockets.on('connection', function(socket){
socket.on('chat message', function(msg){
io.sockets.emit('chat message', msg);
});
});
index.js
var express = require('express');
var router = express.Router();
/* GET Main page. */
router.get('/main', function(req, res) {
res.render('main', { title: 'Main'});
});
It seems that the page is being reloaded because you've forgotten to wrap your client js code with $(document).ready(function() { ... });

Resources