请求被heroku上的cors策略阻止

8tntrjer  于 2023-04-21  发布在  其他
关注(0)|答案(1)|浏览(233)

我做了一个在线的石头剪刀布,我用Heroku部署了我的服务器,用netlify部署了我的客户端。在浏览器控制台,我得到了这个错误:(https://i.stack.imgur.com/ykRGb.png).我已经尝试了每一个修复,我发现,但没有工作或我得到不同的错误
我的服务器代码供参考:

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");
});

出了什么问题,或者有人知道解决办法吗?

1tu0hz3e

1tu0hz3e1#

socket.io 要求您显式定义CORS设置。您可以在最初创建socketio服务器时通过传入第二个参数来完成此操作。在您的情况下,以下应该可以工作:

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

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

相关问题