Search code examples
javascriptreactjsherokucorsxmlhttprequest

request blocked by cors policy on heroku


I made an online rock-paper-scissors and I deployed my server with Heroku and the client with netlify. In the browser console I get this error: (https://i.sstatic.net/ykRGb.png). I've tried every fix that I found but nothing works or I get different error

My server code for reference:

const express = require("express");
const app = express();
const http = require("http");
const { Server } = require("socket.io");
const socketio = require("socket.io");
const cors = require("cors");

app.use(cors());

const server = http.createServer(app);

const routes = require("./routes");
app.use("/", routes);

let players = [];
let otherPlayerChoice = null;
let playerChoice = null;

// const io = new Server(server, {
//   cors: {
//     origin: "https://64372cd23c90670060779932--onlinerock.netlify.app/",
//     methods: ["GET", "POST"],
//   },
// });
const io = socketio(server);

// const cors = require("cors");
const corsOptions = {
  origin: "*",
  credentials: true, //access-control-allow-credentials:true
  optionSuccessStatus: 200,
};

app.use(cors(corsOptions)); // Use this after the variable declaration

io.on("connection", (socket) => {
  console.log(`User Connected: ${socket.id}`);

  players.push(socket.id);

  socket.on("join-room", (number) => {
    socket.join(number);
  });

  const playerNumber = players.indexOf(socket.id);
  socket.emit("playerNumber", playerNumber);

  socket.on("disconnect", () => {
    console.log(`User Disconnected: ${socket.id}`);

    const index = players.indexOf(socket.id);
    players.splice(index, 1);
  });

  socket.on("choice", (data) => {
    console.log(`Player ${data.playerNumber} chose ${data.choice}`);

    // Find the other player
    const otherPlayer = players.find((player) => player !== socket.id);

    // Get the other player's choice
    socket.to(otherPlayer).emit("opposing-player-move", data.choice);
    socket.on("test", (move) => {
      otherPlayerChoice = move.choice;
      playerChoice = data.choice;

      // Determine the winner
      let result;

      if (playerChoice === otherPlayerChoice) {
        result = "It's a tie!";
      } else if (
        (playerChoice === 0 && otherPlayerChoice === 2) ||
        (playerChoice === 1 && otherPlayerChoice === 0) ||
        (playerChoice === 2 && otherPlayerChoice === 1)
      ) {
        result = `Player ${data.playerNumber === 0 ? 1 : 0} wins!`;
      } else {
        result = `Player 2 wins!`;
      }

      // Emit the result to both players
      io.to(move.room).emit("game-result", result);

      // io.to(otherPlayer).emit("game-result", result);
      io.emit("disable-buttons");
    });
  });
});

server.listen(process.env.PORT || 5000, () => {
  console.log("SERVER IS RUNNING");
});

What is wrong or does anybody know a fix for it?


Solution

  • socket.io requires you to explicity define CORS settings. You can do this by passing in a second argument when you initially create the socketio server. In your case, the following should work:

    const io = socketio(server, {
        cors: {
            origin: "*",
            methods: ["GET", "POST"],
            credentials: true
        }
    });
    

    https://socket.io/docs/v3/handling-cors/