0

I am working on a simple socket.io project, and have hit a wall. When I added the script <script src="/socket.io/socket.io.js"></script><script type="text/javascript">var socket = io(); </script> into the head, I was expecting the application to recognize this, but instead I got the error message GET http://localhost:5678/socket.io/socket.io.js and Uncaught ReferenceError: io is not defined in my console. I am using the express framework.

var express = require('express');
var router = express.Router();
var http = require('http').Server(express);
var io = require('socket.io')(http);

/* GET home page. */
router.get('/', function(req, res) {
  res.render('index', { title: 'NodeIM' });
});

io.on('connection', function(socket){
  console.log('a user connected');
  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});

server = http.listen(3000, function() {
    console.log('Listening on port %d', server.address().port);
});

module.exports = router;

HTML:

<html>
   <head>
      <title>NodeIM</title>
      <link rel="stylesheet" href="/stylesheets/style.css">
      <script src="/socket.io/socket.io.js"></script>
      <script type="text/javascript">var socket = io(); </script>
      <style type="text/css"></style>
   </head>
   <body>
      <h1>NodeIM</h1>
      <p>Welcome to NodeIM</p>
      <hr>
      <ul id="messages"></ul>
      <form id="im_form" action=""><input id="m" autocomplete="off"><button>Send</button></form>
   </body>
</html>

NOTE: I've also tried to follow socket.io - ReferenceError: io is not defined and changed my src to src="http://localhost:5678/socket.io/socket.io.js", but it did not fix the issue. I've also tried to use Node.js socket.io.js not found or io not defined, which just showed me another way of requiring socket.io, but doesn't fix the ReferenceError problem I am having

Community
  • 1
  • 1
maudulus
  • 9,035
  • 7
  • 64
  • 101
  • What version of Express are you using? This error is likely because you haven't done the server-side initialization correctly so that the socket.io library hasn't set up the route for `/socket.io/socket.io.js`. – jfriend00 Oct 16 '14 at 18:26
  • I'm using Express version `4.9.0` – maudulus Oct 16 '14 at 18:35

2 Answers2

0

Your usage of /socket.io/socket.io.js for src is correct. However, your setting up of the http server has a typo: var http = require('http').Server(express); should probably be var http = require('http').Server(router);.

mscdex
  • 93,083
  • 13
  • 170
  • 135
-1

As stated in the chat-demo on Socket.io you should put the <script> directly above the closing </body>-tag. Like this:

<script src="/socket.io/socket.io.js"></script>
<script>
    var socket = io();
</script>
</body>
Minato
  • 951
  • 8
  • 20
  • 1
    I see no reason why this should solve a problem any better than the code the OP is already using. I have my client socket.io in the `` section and it works just fine there. – jfriend00 Oct 16 '14 at 18:24