我正在尝试使用react js(with redux)应用程序来设置Signalr。该集线器是一个.Net 4.5应用程序,需要将数据广播到客户端,这是一个react js应用程序。
注意:这是NOT .NET Core应用程序。
这样的协商成功,但是对集线器方法的调用失败,并出现以下错误:
错误:解析协商协商响应时出错。在Object.error(http://localhost:3000/static/js/5.chunk.js:29352:15)在Object.callback [成功](http://localhost:3000/static/js/5.chunk.js:29863:32)着火(http://localhost:3000/static/js/5.chunk.js:16012:33)在Object.fireWith [作为resolveWith](http://localhost:3000/static/js/5.chunk.js:16129:13)完成(http://localhost:3000/static/js/5.chunk.js:21517:20)在XMLHttpRequest。 (http://localhost:3000/static/js/5.chunk.js:21731:19)
一点点挖掘就会发现以下错误,
SyntaxError:JSON中位置0之外的意外令牌http://localhost:3000/static/js/5.chunk.js:29538:26)在Object.callback [成功](http://localhost:3000/static/js/5.chunk.js:29861:30)着火(http://localhost:3000/static/js/5.chunk.js:16012:33)在Object.fireWith [作为resolveWith](http://localhost:3000/static/js/5.chunk.js:16129:13)完成(http://localhost:3000/static/js/5.chunk.js:21517:20)在XMLHttpRequest。 (http://localhost:3000/static/js/5.chunk.js:21731:19)
这样的协商呼叫返回状态200 OK,如下所示,
我的.Net 45项目中的中心类,如下
[HubName("schedule")]
public class SpamHub: Hub
{
public SpamHub()
{
SendSpamEverywhere();
}
public void SendSpamEverywhere()
{
Clients.All.Spams();
}
}
用于SignalR配置的ReactJs中间件如下,
declare global {
interface Window {
jQuery: any
}
}
window.jQuery = $;
require('signalr');
const startSignalRConnection = (connection: SignalR.Hub.Connection) => connection.start()
.then(() => console.info('SignalR connected'))
.fail((error) => console.error('SignalR connection error: ', error))
.catch((error: any) => console.error('SignalR connection error: ', error)); // I always end up here
const signalRMiddleware = (store: any) => (next: any) => async (action) => {
const connection = $.hubConnection();
const spamHubProxy = connection.createHubProxy('schedule');
spamHubProxy.on('spams', function (response) {
console.log('********* SPAM RECEIVED ***********', response);
});
//re-establishthe connection if the connection dropped
connection.disconnected(() => setTimeout(() => {
startSignalRConnection(connection)
}, 10000))
startSignalRConnection(connection);
}
next(action);
}
export default signalRMiddleware;
有人可以帮助我找出此代码有什么问题吗?
经过大量调试,我终于找到了问题。创建集线器连接时,我指的是错误的端口。更改端口号以指向正确的端口号可以解决此问题。