Reputation: 71
I want to implement a SignalR Client in react.
I have an aspnet API which provides SignalR Hub. With a C# SignalR Client I can connect with the hub and send+ receive messages. So it seems that the SignalR Service and CORS are correct.
But when I want to connect with react I get following error:
Debug: HubConnection failed to start successfully because of error 'Error: Unable to connect
to the server with any of the available transports.
WebSockets failed:
Error: 'WebSockets' is disabled by the client.
ServerSentEvents failed: Error: 'ServerSentEvents' is disabled by the client.
LongPolling failed: Error: 'LongPolling' is disabled by the client.'.
My react code:
import { HubConnectionBuilder,LogLevel,HttpTransportType } from '@microsoft/signalr';
import { getUserAccessToken } from '../auth/UserManager';
export function ConnectToSignalR(){
return new HubConnectionBuilder()
.withUrl('http://localhost:18198/messagehub',options=> {
options.skipNegotiation=false;
options.transport = HttpTransportType.WebSockets;
options.accessTokenFactory = ()=>getUserAccessToken();
return options;})
.withAutomaticReconnect()
.configureLogging(LogLevel.Trace)
.build();
}
export function startSignalRConnection(signalRConnection){
if (signalRConnection) {
signalRConnection.start()
.then(result => {
console.log('SingnalR','Connected!');
signalRConnection.on('TimeWarningMessage', message => {
console.log(message);
});
})
.catch(e => console.log('SingalR Connection failed: ', e));
}
}
Code is called in App.js (main component) of react app via useEffect hook once application starts.
What is meant by 'is disabled by the client'? Is there a way those things can be disabled? Browser I tested is current version of Edge and Chrome, both have same issue. Version of react package is 8.0.7 and in Backend on asp net core side, I am using NET8
Upvotes: 1
Views: 81
Reputation: 71
I just found out, that my options were incorrect. If i use another example from the internet it works. See:
export function ConnectToSingalR(){
return new HubConnectionBuilder()
.withUrl('http://localhost:18198/messagehub', {
accessTokenFactory: () => {
return getUserAccessToken();
}
})
.withAutomaticReconnect()
.configureLogging(LogLevel.Trace)
.build();
}
But I dont understand why the option part produces this error. If it is not correct ok, my fault but i just expected a better and understandable error message....
Upvotes: 2