Patrick Mcmahon
Patrick Mcmahon

Reputation: 106

Socket.io will not work unless being run locally

I have a game made with React & Node, where it uses almost exclusively sockets to handle the events. Now, everything works exactly as I need it to when I run it locally, but as soon as I host it, I get all sorts of nothing happening, and I could really use a hand. I searched far and wide for an answer with no luck. I think I may know where the problem is, just not how to fix it.

SERVER

const express = require("express");
const app = express();
const server = require("http").Server(app);
var io = require("socket.io")(server);
const path = require("path");
const sockets = require("./sockets_controller");

app.use(express.static(`${__dirname}/../build`));

io.of("/create").on("connection", socket => {

  socket.on("create game", user => sockets.createGame(user, socket));

});

...More namepaces and event listeners...


server.listen(4001, () => console.log(`server running on port 4001`));

app.get("*", (req, res) => {
  res.sendFile(path.join(__dirname, "../build/index.html"));
});

Again, works perfect on localhost: but heres how I connect on the front end

Each of my components have a namespace associated with them, so in each component that uses sockets I have

import socketIOClient from "socket.io-client";
const socket = socketIOClient("http://localhost:4001/NAMEPSACE");

I saw on here that I should try to just use socketIOClient(), which SORTA works, but I lose my namespace and whatever I emit goes unheard by the sockets listening on the server.

I get the following error when I load the hosted version

The origin 'http://www.mywebsite.com' did not find 'http://www.mywebsite.com' in the Access-Control-Allow-Origin response header for cross-origin  resource at MY_IP

I have to imagine that I have to change localhost to something, but I just cant be sure.

EDIT: I have also tried socketIOClient("http://IP:4001/NAMEPSACE") and just socketIOClient("http://IP/NAMEPSACE") and still nothing is working

Upvotes: 0

Views: 326

Answers (1)

Patrick Mcmahon
Patrick Mcmahon

Reputation: 106

Okay, so I got it to work by changing const socket = socketIOClient("http://localhost:4001/NAMEPSACE")

to

const socket = socketIOClient('/NAMESPACE)

Upvotes: 1

Related Questions