如何解决Heroku Nodejs 与 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",[]);
知道为什么会这样吗? 谢谢!
解决方法
据我所知,vercel 仅支持无服务器功能。您不能使用任何套接字、websocket 库。您可以在此官方 link 中从他们的 github 中了解更多详细信息。我希望这将有所帮助。祝你好运
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。