Babylon.js连接Colyseus服务器时出现CORS错误求助
Babylon.js 连接 Colyseus 服务器时的 CORS 错误排查求助
我在尝试将Babylon.js与Colyseus服务器连接时遇到了CORS错误,错误截图如下:
以下是服务端和客户端的代码,我已在请求和响应中配置了相关CORS设置,但问题仍未解决,求帮忙排查。
服务端文件 - index.js
// server/index.js import express from 'express'; import http from 'http'; import { Server } from 'colyseus'; import GameRoom from './rooms/GameRoom.js'; import { matchMaker } from "@colyseus/core"; const app = express(); const port = process.env.PORT || 2567; // CORS middleware app.use((req, res, next) => { res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000'); res.setHeader('Access-Control-Allow-Credentials', 'true'); res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); if (req.method === 'OPTIONS') { res.sendStatus(204); // No Content } else { next(); } }); // Configure CORS headers matchMaker.controller.getCorsHeaders = function (req) { return { 'Access-Control-Allow-Origin': '*', // Allow all origins 'Vary': '*', // Vary by all headers (or specify specific ones if needed) // Other headers can be added here if needed }; }; // Create HTTP & WebSocket servers const server = http.createServer(app); const gameServer = new Server({ server });
客户端文件 - colyseusclient.js
import * as Colyseus from "colyseus.js"; // Extend Colyseus client to set withCredentials class CustomClient extends Colyseus.Client { constructor(url) { super(url); } createRequest(route, method = "GET", options = {}) { options.credentials = 'include'; // Enable sending credentials with each request. return fetch(route, options); } } const client = new CustomClient("ws://localhost:2567"); console.log("client object" ,client) let room; fetch("http://localhost:2567/", { credentials: "include" }) .then(response => console.log("Server Response:", response)) .catch(error => console.error("Connection error:", error)); export async function connectToRoom() { try { room = await client.joinOrCreate("game_room"); // 错误发生在此处
排查方向建议
- CORS配置冲突:你在Express中间件里指定了
Access-Control-Allow-Origin为http://localhost:3000,但matchMaker配置里又设为*。当客户端开启credentials: 'include'时,*是不被浏览器允许的,必须指定具体域名。把matchMaker的CORS配置改成和Express一致的http://localhost:3000。 - 改用Colyseus官方CORS配置:Colyseus Server初始化时支持直接配置CORS,建议删掉自定义的Express CORS中间件,改用官方方式避免冲突:
const gameServer = new Server({ server, cors: { origin: "http://localhost:3000", credentials: true } }); - WebSocket连接校验:确认客户端WebSocket URL协议与前端环境匹配(HTTP对应
ws://,HTTPS对应wss://),且域名端口与服务端允许的完全一致。 - 预检请求检查:打开浏览器开发者工具,查看OPTIONS预检请求的响应头,确认
Access-Control-Allow-Origin、Access-Control-Allow-Credentials等字段是否正确返回,有没有被其他中间件覆盖。 - 代码完整性:客户端
connectToRoom函数未写完,排查是否存在语法错误导致请求异常。
内容的提问来源于stack exchange,提问作者Ishita Amod
相关产品推荐
相关产品推荐

