'error: websocket.js:84 WebSocket connection to 'ws://localhost:5000/socket.io/?EIO=4&transport=websocket' failed:
I am building a realtime chat application using reactJs, node and socket.io . But i am getting the error that websocket connection has failed. This is the error which i am getting in the console websocket.js:84 WebSocket connection to 'ws://localhost:5000/socket.io/?EIO=4&transport=websocket' failed:
This is client side code
let socket;
const Chat = ({ location }) => {
useEffect(() => {
const { name, room } = queryString.parse(location.search);
socket = io(ENDPOINT, { transports: ['websocket'] })
setName(name);
setRoom(room);
socket.emit('join', { name, room }, () => {
})
return () => {
socket.emit('disconnect');
socket.off();
}
}, [ENDPOINT, location.search])
useEffect(() => {
socket.on('message', (message) => {
setMessages([...messages, message]);
})
}, [messages]);
const sendMessage = (event) => {
event.preventDefaut();
if (message) {
socket.emit('sendMessage', message, () => setMessage(''));
}
}
console.log(message, messages);
return (
<div className="outerContainer">
<div className="container" >
<input value={message} onChange={(event) => setMessage(event.target.value)} onKeyPress={event => event.key === 'Enter' ? sendMessage(event) : null} />
</div>
</div>
)
}
export default Chat;
and this is server side code
const { addUsers, removeUser, getUser, getUsersInRoom } = require('./users')
const PORT = process.env.PORT || 5000
const router = require('./router');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
io.on('connection', (socket) => {
socket.on('join', ({ name, room }, callback) => {
const { error, user } = addUsers({ id: socket.id, name, room });
if (error) return callback(error);
socket.emit('message', { user: 'admin', text: `${user.name} , welcome to room ${user.room}` });
socket.broadcast.to(user.room).emit('message', { user: 'admin', text: `${user.name} has joined` });
socket.join(user.room);
callback();
})
socket.on('sendMessage', (message, callback) => {
const user = getUser(socket.id);
io.to(user.room).emit('message', { user: user.name, text: message });
callback();
})
socket.on('disconnect', () => {
console.log("user have left");
})
})
Solution 1:[1]
server side. in index.js file use check(?) (user?.room)
io.to(user?.room).emit('message', { user: user.name, text: message });
Solution 2:[2]
I think adding headers to the request might solve the issue. I read it in the socket.io documentation. I hope this would help your issue. Let me know how it goes. Example:
socket = io(ENDPOINT, {
cors: {
origin: "http://localhost:5000",
credentials: true
},transports : ['websocket'] });
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ali Raza |
| Solution 2 | Myo |
