I'm a newbie to Socket.IO, I did the chat tutorial of the docs and the "homework" of the chat app to understand how it works, now I'm trying to connect an NodeJS server and a React App with a Socket. I've spent all day trying to do this, but I'm getting this error:
GET http://localhost:4000/?EIO=4&transport=polling&t=NYW26Ea 404 (Not Found)
The itention of my app is show an update of time, I'm using socket to update time on screen each one second. Here's my Server.js file, and yes, it is pretty simple:
const express = require("express")
const http = require("http")
const socketIO = require("socket.io")
var cors = require('cors')
const PORT = 4000;
const routes = require("./routes/index")
const app = express()
app.use(cors())
app.use(routes)
const server = http.createServer(app)
const io = socketIO(server)
let interval
io.on("connection", (socket) => {
console.log("New client connected!")
if(interval) {
clearInterval(interval)
}
interval = setInterval(() => getApiAndEmit(socket), 1000)
socket.on("disconnect", () => {
console.log("Client is disconnected")
clearInterval(interval)
})
})
const getApiAndEmit = socket => {
const response = new Date()
socket.emit("from-api", response)
}
app.listen(PORT, () => console.log(`Application up and running on ${PORT}`))
If I visit the route I created with express it works fine.
And here is my App.js file:
import React, { useState, useEffect } from "react";
import socketIOClient from "socket.io-client";
const ENDPOINT = "http://127.0.0.1:4000";
function App() {
const [response, setResponse] = useState("");
useEffect(() => {
const socket = socketIOClient(ENDPOINT);
socket.on("from-api", data => {
setResponse(data);
});
}, []);
return (
<p>
It's <time dateTime={response}>{response}</time>
</p>
);
}
export default App;
Should I create a route for SocketIO or what?