skip to Main Content

I am working on a chatting web app project where I am using socket io library of nodejs. When I run it on the browser i face "Loading failed for the with source “http://localhost:8000/socket.io/socket.io.js”" error.

here is the code for my server js

const io = require('socket.io')(8000);

const prompt = require("prompt-sync")();

const users={};

io.on('connection' , socket =>{
    socket.on('new-user-joined', name=>{
        users[socket.id] = name;
        socket.broadcast.emit('user-joined' , name);
    })

    socket.on('send' , message =>{
        socket.broadcast.emit('receive', {message: message, name: users[socket.id]});

    })

    socket.on("connect_error", (err) => {
        console.log(`connect_error due to ${err.message}`);
    })
    
});

here is the html header

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ichat</title>
    <link rel="stylesheet" href="style.css">
    <script defer src="http://localhost:8000/socket.io/socket.io.js"></script>
    <script defer src="js/client.js"></script>
</head>

Sometimes when I rearrange the script tags in the body (without defer) the web app starts working then after a while throws the same error again. I am getting frustrated with this. Please help me, what should I do

2

Answers


  1. You can’t use localhost, there will be CORS errors.

    Use the script served by CDN:

    <script src="https://cdn.socket.io/4.7.5/socket.io.min.js" integrity="sha384-2huaZvOR9iDzHqslqwpR87isEmrfxqyWOF7hr7BY6KG0+hVKLoEXMPUJw3ynWuhO" crossorigin="anonymous"></script>
    

    See the docs here https://socket.io/docs/v4/client-installation/

    Login or Signup to reply.
  2. Error is because of the src="http://localhost:8000/socket.io/socket.io.js&quot; remove <script defer src="http://localhost:8000/socket.io/socket.io.js"></script> try this below code instead.

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.dev.js"></script>
    <script src="/socket.io/socket.io.js"></script>
    

    Documentation for socket
    :- https://socket.io/docs/v4/client-installation/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search