'SocketIo: Unable to emit event from react frontend to node backend
I have a basic react app setup on 3000 with a socketio server running via express on 5000. My Problem is that while I'm able to connect to the socketio server and receive events emitted from the server on the client, I am not able to emit events from the client to the server.
I've found this similar question, though it doesn't help because in that case the user had failed to reference the correct socket object, a problem which I am not having here.
Here's the part in my react app where I talk to the server:
import React, { useState, useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { useChat } from '../contexts/ChatContext';
import queryString from 'query-string';
import io from 'socket.io-client';
let socket;
const Chat = () => {
const location = useLocation();
const { chatState } = useChat();
console.log('chat context', chatState);
const ENDPOINT = 'http://localhost:5000';
useEffect(() => {
// const { name, room } = queryString.parse(location.search);
socket = io(ENDPOINT);
socket.on('connect', () => {
console.log('socket connected');
console.log(socket);
});
socket.emit('test', 'test');
}, [chatState, ENDPOINT]);
return (
<div>
<h1>Welcome to Chat</h1>
</div>
);
};
export default Chat;
And here's my server:
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const cors = require('cors');
const app = express();
const httpServer = http.createServer(app);
const io = new Server(httpServer, {
cors: {
origin: '*',
methods: ['GET', 'POST'],
},
});
io.on('connection', (socket) => {
console.log('we have a connection');
socket.on('test', (args) => console.log(args));
socket.disconnect(() => console.log('a user disconnected'));
});
app.use('/', require('./router'));
const PORT = process.env.PORT || 5000;
httpServer.listen(PORT, () => console.log(`Listening on port ${PORT}`));
You can see that I am emitting 'test' event type with data payload 'test' and listening for 'test' via socket.on in the server. When my component loads, I see "we have a connection" and nothing else.
full repo here
Solution 1:[1]
As about14sheep said, I was immediately disconnecting instead of listening for a disconnect.
The corrected server code is:
io.on('connection', (socket) => {
console.log('we have a connection');
socket.on('test', (args) => console.log(args));
socket.on('disconnect', () => {
console.log('a user disconnected');
});
});
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 | Corey Munn |
