Heroku Nodejs 与 Vercel Nodejs

Heroku Nodejs vs Vercel Nodejs

我在 Heroku 中托管了一个服务器。此外,客户端(React)托管在 Vercel 中。这种组合非常有效!但是,出于好奇,我尝试在 Vercel 中托管服务器端脚本。然后,当我尝试连接到 Vercel 托管服务器时,客户端返回此错误 Access to XMLHttpRequest at 'https://socketio-vercel.vercel.app/socket.io/?EIO=4&transport=polling&t=NVeP_Ax' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.(我正在 localhost:3000 中测试)

服务器端代码(在 Heroku 和 Vercel 中都是一样的)->

"use strict";

const express = require("express");
const socketIO = require("socket.io");

const PORT = process.env.PORT || 3000;
const INDEX = "/index.html";

const server = express()
  .use((req, res) => res.sendFile(INDEX, { root: __dirname }))
  .listen(PORT, () => console.log(`Listening on ${PORT}`));

const io = socketIO(server, {
  cors: {
    origin: "http://localhost:3000",
    methods: ["GET", "POST"],
  },
});

io.on("connection", (socket) => {
  console.log("Client connected");
  socket.on("disconnect", () => console.log("Client disconnected"));
});

setInterval(() => io.emit("time", new Date().toTimeString()), 1000);

客户端代码(如果服务器由 Heroku 托管)(工作中)->

useEffect(() => {
if (shouldStart) {
  axios.get("api/sync").then((response) => {
    setMessages(response.data);
    const socket = io("wss://radiant-mountain-09008.herokuapp.com");
    socket.on("connect", () => {
      console.log("connected"); // "G5p5..."
    });
    socket.on("time", (msg) => {
      console.log(msg);
    });
  });
}
}, [shouldStart]);

客户端代码(如果服务器由 Vercel 托管)->

useEffect(() => {
if (shouldStart) {
  axios.get("api/sync").then((response) => {
    setMessages(response.data);
    const socket = io("wss://socketio-vercel.vercel.app");
    socket.on("connect", () => {
      console.log("connected"); // "G5p5..."
    });
    socket.on("time", (msg) => {
      console.log(msg);
    });
  });
}
}, []);

知道为什么会这样吗? 谢谢!

据我所知,vercel 仅支持无服务器功能。您不能使用任何套接字、websocket 库。您可以在官方 link 从他们的 github 中了解更多详细信息。我希望这将有所帮助。祝你好运