Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

1K
Views
Using socket io with express and ejs

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

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!