Connection refused error after deploying socket io app to cloudflare #4565
-
Server code: const express = require("express"); app.use(cors()); const server = http.createServer(app); const io = new Server(server, { io.on("connection", (socket) => { socket.on("join_room", (data) => { }); server.listen(8080, () => { Client side: import "./App.css"; const socket = io.connect("http://localhost:8080"); function App() { const joinRoom = () => { return ( <input placeholder="Room Number..." onChange={(event) => { setRoom(event.target.value); }} /> Join Room <input placeholder="Message..." onChange={(event) => { setMessage(event.target.value); }} /> Send Message Message:{messageReceived} ); } export default App; But I am getting the following error after hosting it on cloudflare. Same this works fine in local. polling.js:311 GET http://localhost:8080/socket.io/?EIO=4&transport=polling&t=OKjuPmR net::ERR_CONNECTION_REFUSED Can anyone please help me? Thanks in advance |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
Hi! I see you have const socket = io.connect("http://localhost:8080/"); Shouldn't it be something like: const socket = io.connect("<cloudflare URL>"); |
Beta Was this translation helpful? Give feedback.
-
The problem you have is that you have the production client side uses the local url for the server, as said by @darrachequesne You can do this by deploying the the server first. Copy the Cloudflare server url. As you are using react, you can create a local utility function to check if the env is
export default function getServerUrl() {
if (process.env.NODE_ENV === "development") {
return "http://localhost:8080"; // local server url
} else {
return ""; // Cloudflare server url
}
} And in the client side, you could use this as: const socket = io.connect(getServerUrl()); This way you can set the url of the server dynamically and you don't have to worry about the conflicts of the production and development server urls. |
Beta Was this translation helpful? Give feedback.
Hi! I see you have
Shouldn't it be something like: