I really can't get socket.io to work after deployment.
Backend:
import * as dotenv from "dotenv";
import express from "express";
import mongoose from "mongoose";
import cors from "cors";
import bodyParser from "body-parser";
import { Server } from "socket.io";
dotenv.config();
const app = express();
app.use(bodyParser.json({ limit: "15mb", extended: true }));
app.use(bodyParser.urlencoded({ limit: "15mb", extended: true }));
app.use(cors());
app.get("/", (req, res) => res.send("My app API"));
const PORT = process.env.PORT || 5000;
const SOCKET_IO_PORT = process.env.SOCKET_IO_PORT || 5500;
let server = app.listen(SOCKET_IO_PORT, () => {
console.log("Socket.io server running on port :" SOCKET_IO_PORT);
});
const io = new Server(server, {
cors: { origin: "https://myapp.pages.dev" },
});
mongoose
.connect(process.env.CONNECTION_URL)
.then(() =>
app.listen(PORT, () => console.log(`Server running on port : ${PORT}`))
)
.catch((error) => console.log(error.message));
Frontend:
socket.current = io("https://myapp-api-production.up.railway.app");
socket.current?.on(
"getMessage",
(...) => {
...
}
);
Browser network tab:
Request URL: https://myapp-api-production.up.railway.app/socket.io/?EIO=4&transport=polling&t=OO7eSMV
Request Method: GET
Status Code: 404
Response:
Cannot GET /socket.io/
Server deployment log:
- Socket.io server running on port :5698
- Server running on port : 7777
CodePudding user response:
You're creating two separate HTTP servers (by calling app.listen()
twice). It looks like your frontend code is targeting the Express server, and not the socket.io
server.
My suggestion would be to just use one HTTP server listening on PORT
:
let server = app.listen(PORT, () => {
console.log("Server running on port :" PORT);
});
(and remove the call to app.listen()
in the Mongoose then()
handler).