0

I'm trying to incorporate a live user count on my website http://clickthebutton.herokuapp.com which uses Express JS. When trying to install socket.io I get this error:

GET /socket.io/socket.io.js 404 1.911 ms - 1091

Yes, I have used 'npm install socket.io --save'

I have looked around for answers, tried them and nothing has helped. If anyone thinks they know what's happening, a response would be well appreciated! Here's my code:

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 io = require('socket.io')(app);

var routes = require('./routes/index');
var users = require('./routes/users');

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

var server = app.listen(app.get('port'), function () {
    console.log('server listening on port ' + server.address().port);
})
var io = require('socket.io').listen(server);
// 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(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);

// 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;

index.ejs

           <!-- socket.io -->
           <script src="socket.io/socket.io.js"></script>
           <script type="text/javascript">
            var socket = io.connect();
           </script>
         </div>
    </center>
   </body>

routes/index.js

var express = require('express');
var router = express.Router();
var redis = require('redis'), client = redis.createClient(secret, "secret"); client.auth("secret", function() {console.log("Connected!");});
var app = express();
var server = require('http').Server(app);
var http = require('http');

var io = require('socket.io').listen(server);

io.on('connection', function(socket){
  console.log('a user connected');
    console.log(Object.keys(io.sockets.connected));
});


io.on('connection', function (socket) {
  console.log('Socket.io connected!')
});

I only copy/pasted the code that referenced socket.io

Thanks!

William G
  • 1
  • 1
  • 4
  • What's your setup? You mention a publicly hosted site, then you show code that only listens on localhost/127.0.0.1. Also the code on your hosted sites has lots of references to localhost:3001 and port 3001, when the code you pasted used port 8080... Please provide a consistent set of code and live example. – jcaron Sep 24 '16 at 15:11
  • Still not consistent with what you have on your hosted site (where the error doesn't even match). – jcaron Sep 24 '16 at 15:17
  • @jcaron I haven't pushed my edits onto Heroku, if I can get it working locally using npm start and localhost I can adapt it to work on Heroku. – William G Sep 24 '16 at 15:27
  • Set up a snippet or a jsFiddle, then, and don't quote your hosted site if it's not relevant to the question. – jcaron Sep 24 '16 at 15:29

1 Answers1

3

In app.js alone you're creating three instances of socket.io, and once again in routes/index.js. There should be only one throughout your entire app.

A common setup for Express looks like this:

var app    = require('express')();
var server = app.listen(app.get('port'), function () {
  console.log('server listening on port ' + server.address().port);
});
var io = require('socket.io')(server);

If you need to reference either app, server or io in other files, you need to pass it as a variable.

EDIT: because you're using an express-generator based setup, the HTTP server will be created in bin/www and not app.js. In that case, you also need to create the socket.io server there:

/**
 * Create HTTP server.
 */

var server = http.createServer(app);
var io = require('socket.io')(server); // add this line

Again, if you need to reference io somewhere else in your codebase, you need to pass it along from there.

robertklep
  • 198,204
  • 35
  • 394
  • 381
  • I've limited referencing socket.io in my index.js but it's still returning a 404 error. – William G Sep 24 '16 at 16:08
  • Since your `app.js` is exporting `app`, do you also have a `bin/www` that may start an HTTP server? – robertklep Sep 24 '16 at 16:15
  • `npm start` triggers `node .bin/www`. – William G Sep 24 '16 at 16:41
  • In that case, you _probably_ need to create the `socket.io` server in `bin/www` (because if we're talking `express-generator`, that's where the HTTP server gets created and started). – robertklep Sep 24 '16 at 16:43
  • How would I go about that? – William G Sep 24 '16 at 16:47
  • Thanks so much! Had to get some help from http://stackoverflow.com/questions/24609991/using-socket-io-in-express-4-and-express-generators-bin-www but it works! – William G Sep 24 '16 at 21:16
  • the trick is: var io = require('socket.io')(server); AND server = require('express')().listen(port,cb); ->after .listen() you get the server instance which works with socket.io - the official socket.io tutorial didn't work. thx – Suisse Sep 18 '18 at 16:00