4

Hey so i just started to learn node js today and i am using express with ejs and trying to add a socket io server / chat but i can't seem to work out why i can't get it to work.

The page loads but does not connect to the socket server.

server.js:

const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const app = express();

// EJS
app.use(expressLayouts);
app.use(express.static("public"));
app.set('view engine', 'ejs');

// Routes
app.use('/', require('./routes/index.js'));
app.use('/chat', require('./routes/chat.js'));
app.use((req, res, next) => res.redirect('/'));

const listener = app.listen(process.env.PORT, () => {
  console.log('Your app is listening on port ' + listener.address().port)
});

routers/chat.js

const express = require('express');
const router = express.Router();
const server = require('http').createServer();
const io = require('socket.io')(server);

// Chat Page
router.get('/chat', (req, res) => {
  res.render("chat/chat");
});

io.on('connection', function(socket) {
  console.log('a user connected');
  socket.on('chat message', function(msg) {
    console.log('message: ' + msg);
  });
});

module.exports = router;

views/chat/chat.ejs:

<form action="">
  <input id="m" autocomplete="off" /><button>Send</button>
</form>

<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
  $(function () {
    var socket = io();
    
    $('form').submit(function(){
      socket.emit('chat message', $('#m').val());
      $('#m').val('');
      return false;
    });
  });
</script>

Error: Uncaught ReferenceError: io is not defined

Christian Moen
  • 907
  • 1
  • 13
  • 29
incipriata
  • 41
  • 3

1 Answers1

1

You cannot source /socket-lib/socket.io.js,

you must source http://yourwebsite.com:12345/socket.io/socket.io.js.

bascily, you'll need to provide full source for the server adress.

The server automatically does the rest for you.

Source: https://stackoverflow.com/a/12160485/3010171

also. you might try out ./socket-lib/socket.io.js with a . before the slash

Christian Moen
  • 907
  • 1
  • 13
  • 29