Getting server error on connection with socket.io

95 Views Asked by At

I'm making a project that is a chat in real time with socket.io. I alredy make a part of the server and the html file. When i execute in terminal, the code node server.js, the page is render, but it should to print a message in terminal with the id of socket.

I put this code in the server.js to display a message in the terminal when the page is render:

io.on('connection', socket => {
    console.log(`Socket conectado: ${socket.id}`);
});

But when i reload the page, after execute the node in terminal, does'nt apears. So i put a code in the html file to verify if the problem is with the connection

socket.on('connect_error', err => {
            console.log(`Erro de conexão: ${err.message}`);
        });

And when i reload the page, in console, show the message server error, so i thought the problem could be the CDN url of socket io, but i try to put others urls and i'm get the same error, i try change the port too. This is the full code of server.js

const express = require('express');
const path = require('path');
const cors = require('cors');

const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);

app.use(cors());
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'public'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

app.use('/', (req, res) => {
    res.render('index.html');
});

io.on('connection', socket => {
    console.log(`Socket conectado: ${socket.id}`);
});

app.listen(3000);

And this is the html file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat da Rocketseat</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.6.1/socket.io.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>

    <link rel="stylesheet" href="style.css">
</head>
<body>
    <form id="chat">
        <input type="text" name="username" placeholder="Digite seu usuário">
        <div class="messages"></div>
        <input type="text" name="message" placeholder="Digite sua mensagem">
        <button type="submit">Enviar</button>
    </form>
    
    <script type="text/javascript">

        var socket = io('http://localhost:3000');

        socket.on('connect_error', err => {
            console.log(`Erro de conexão: ${err.message}`);
        });

    </script>
</body>
</html>
1

There are 1 best solutions below

1
sachin On

Add <script src="http://localhost:3000/socket.io/socket.io.js"></script> in your Head tag.

Most of the time this will solve the issue as the page has to load the s