【问题标题】:Heroku Nodejs vs Vercel NodejsHeroku Nodejs vs Vercel Nodejs
【发布时间】:2021-05-30 04:21:42
【问题描述】:

我在 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);
    });
  });
}
}, []);

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

【问题讨论】:

    标签: node.js heroku socket.io vercel


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-05-14
      • 1970-01-01
      • 2016-09-03
      • 2021-01-07
      • 2017-01-26
      • 2020-12-29
      • 1970-01-01
      • 2017-10-10
      • 1970-01-01
      相关资源
      最近更新 更多