错误屏幕截图 当我尝试连接到 colyseus 服务器时,出现 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
});
这是服务器的索引文件,这里我也添加了cors设置 客户端文件 - 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"); => error is here
我尝试在请求中添加所有cors并尽我所能
您在 Express 中间件中将
Access-Control-Allow-Origin
标头设置为 http://localhost:3000,但在 matchMaker.controller.getCorsHeaders
函数中使用通配符 (*)。当 Access-Control-Allow-Credentials
设置为 true
时,Access-Control-Allow-Origin
标头不能为通配符。
如果你更换它应该可以工作
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
};
};
使用以下代码:
// Configure CORS headers for Colyseus matchmaker
matchMaker.controller.getCorsHeaders = function (req) {
return {
'Access-Control-Allow-Origin': 'http://localhost:3000', // Match the allowed origin
'Access-Control-Allow-Credentials': 'true', // Allow credentials
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS'
};
};