I'm using node.js, ejs, express, mysql and socket.io. My server looks like this (index.js):
module.exports = function(io) {
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'root',
password: '',
database: 'chat'
});
router.get('/chat/:channel_name', (req, res, next) => {
var channel_name = req.params.channel_name;
// get the countries from the database so we make sure the users are connecting to the correct channel to chat, else redirect to /chat
pool.getConnection((err, connection) => {
if(err) return console.log(err);
connection.query('SELECT * FROM channel WHERE channel_name = ?', channel_name, (err, rows) => {
if(err) return console.log(err)
if(!rows.length){
return res.redirect('/chat')
}
res.render('channel', {channel_name: rows[0].channel_name})
var channel = io.of(`/chat/${rows[0].channel_name}`);
channel.on('connection', function(socket){
socket.join(rows[0].channel_name)
channel.to(rows[0].channel_name).emit('say hi', 'Hi from ' + rows[0].channel_name + '!');
});
});
});
});
router.get('/chat', function(req, res, next) {
res.render('chat');
});
return router;
}
Client:
<!DOCTYPE html>
<html>
<head>
<title><%= channel_name %></title>
</head>
<body>
<div id="message"></div>
</body>
</html>
<script src="/js/lib/jquery/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>
<script>
var socket = io(`/chat/<%= channel_name %>`);
socket.on('say hi', function(data){
$('#message').append(`<div>${data}</div>`)
})
</script>
Basically, when I restart the server, and try, for example: /chat/uk
, it shows on the html page: Hi from uk!
However, after restarting the page 10 times, (on the 11th time) the browser keeps loading and it shows GET /chat/uk - - ms - -
on the command prompt, why is this happening?
Also, is this the right way to use namespaces? I want to create multiple channels(namespaces) that users will connect and then chat 1 on 1 privately (rooms)