我已在 next.js 组件中配置了 Signal R 连接。
import { useState } from 'react';
import { HubConnectionBuilder } from '@microsoft/signalr';
import { useGlobalState } from '@/context/GlobalStateContext';
interface ConfigProps {
config: Config
}
export interface Config {
connect: boolean
}
const SignalRComponent: React.FC<ConfigProps> = ({config}) => {
const [connected, setConnected] = useState<boolean>(false);
const { state, dispatch } = useGlobalState();
const connection = new HubConnectionBuilder()
.withUrl(`${state.config.url}/${state.config.endpoint}/${state.config.gamingserver}-${state.config.playerid}`) // Replace with your SignalR hub URL
.build();
const connect = async () => {
try {
await connection.start();
setConnected(true);
connection.on("ReceiveMessage", (user: string, message: string) => {
console.log(`${user}: ${message}`);
});
console.log("Connected to SignalR");
} catch (err) {
console.log(`${state.config.url}/${state.config.endpoint}/${state.config.gamingserver}-${state.config.playerid}`)
}
};
const disconnect = async () => {
try {
await connection.stop();
setConnected(false);
console.log("Disconnected from SignalR");
} catch (err) {
console.error("Error disconnecting from SignalR", err);
}
};
return (
<>
{
config.connect ? (<button className='bg-green-200 hover:bg-green-300 text-green-800 font-bold py-2 px-4 rounded' type="submit" onClick={connect}>Connect</button>)
: (<button className='bg-red-200 hover:bg-red-300 text-red-800 font-bold py-2 px-4 rounded' onClick={disconnect}>Disconnect</button>)
}
</>
);
};
export default SignalRComponent;
withUrl 值由用户在表单中输入,这意味着它是动态的。
尝试建立连接时,我收到 CORS 错误
从源“http://localhost:4200”获取“https://example.co.za/testing/332-4255/negotiate?negotiateVersion=1”的访问已被 CORS 策略阻止:响应预检请求未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明响应满足您的需求,请将请求模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。
问题不在于服务器,我已经检查过。 我已经尝试过中间件方法,但它不起作用,有任何关于如何解决此问题的线索吗?
看起来像是典型的 CORS 问题。由于您确信服务器设置正确,因此可以尝试以下几项操作:
// pages/api/proxy.ts
export default async (req, res) => {
const response = await fetch(`https://example.co.za/${req.query.endpoint}`, {
method: req.method,
headers: {
...req.headers,
'Origin': undefined // remove the origin header
},
body: req.body
});
const data = await response.json();
res.status(response.status).json(data);
};
const connection = new HubConnectionBuilder()
.withUrl(url, { withCredentials: true })
.build();