All versions installed of socket.io and socket.io-client are the same in my mern app.
Here is my server code:
const app = express();
mongoose.connect(MONGOOSE_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => {
console.log(`MongoDB connected successfully`);
}).catch((error) => console.log(`${error} did not connect`));
const server = http.createServer(app);
const io = new Server(server, console.log('io is being called'));
io.on('connection', (socket) => {
console.log(socket.id)
})
server.listen(3005, () => {
console.log(`Server is listening on PORT 3005`);
});
here is my client code:
import io from 'socket.io-client';
const socket = io('http://localhost:3005');
socket.on('connect', () => {
console.log('you connected!')
})
Why doesn’t it show the socket io connection was made when I npm start both my client and server?
On my server side, it console logs that:
- io is being called,
- Server is listening on PORT 3005,
- MongoDB connected successfully
Does anyone know if I’m missing anything?
3
Answers
The reason it wasn't being made was because my socket.io-client code was placed in an individual js file.
In order for it to run, it needs to be in a component on the client side rendered in App.js.
Once I did that, the connection was made between server and client.
try it
There is no issue in your code.
console.log('you connected!')
will NOT show up in server side logs because it is client side code.You have to check the client side logs in the browser you are using to open the client in order to view
you connected!
. The shortcut to Dev Tools is F-12 in Google Chrome for example.