socket.io在本地主机上工作时遇到问题,但在部署到heroku时却没有问题。
在客户端,我有这个:
import socketIOClient from "socket.io-client";
const socket = socketIOClient("http://127.0.0.1:4001");
并在服务器端:
const http = require("http");
const socketIo = require("socket.io");
const server = http.createServer(app);
const io = socketIo(server);
io.on("connection", socket => {
console.log("New client connected");
socket.on("chat message", function(msg) {
console.log("message: " + msg);
io.emit("chat message", msg);
});
这在本地主机上完美运行,但是在Heroku上会引发CORS错误。为了解决这个问题,我尝试更改此行:
const socket = socketIOClient("http://127.0.0.1:4001");
到
const socket = socketIOClient("https://radiant-retreat-86258.herokuapp.com/");
(这是应用程序的URL)。
我也尝试将代码更改为此:
import io from "socket.io-client";
const socket = io();
这两个选项都消除了CORS错误,但是网络显示连续的403,并且套接字实际上未执行应做的事情。