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
You can’t use localhost, there will be CORS errors.
Use the script served by CDN:
See the docs here https://socket.io/docs/v4/client-installation/
Error is because of the src="http://localhost:8000/socket.io/socket.io.js" remove
<script defer src="http://localhost:8000/socket.io/socket.io.js"></script>
try this below code instead.Documentation for socket
:- https://socket.io/docs/v4/client-installation/