下面的前端 typescript 代码
import { HubConnection, HubConnectionBuilder, HubConnectionState } from '@microsoft/signalr';
export class WechatMpQrComponent implements OnInit {
private connection: HubConnection;
constructor() {}
ngOnInit(): void {
this.connection = new HubConnectionBuilder()
.withUrl(`${environment.baseUrl}/hubs/wechat-mp-auth`)
.build();
}
async start(): Promise<void> {
if (this.connection.state !== HubConnectionState.Disconnected) {
return;
}
this.status = WechatMpQrStatus.Loading;
try {
await this.connection.start();
await this.connection.send('Initialize');
} catch (e) {
this.onError(`建立连接失败 ${(e as Error)?.message}`);
}
}
}
经常出现下面的错误
建立连接失败:Unable to connect to the server with any of the available transports. WebSockets failed: Error: There was an error with the transport. ServerSentEvents failed: Error: Error occurred LongPolling failed: Error
在创建 HubConnection 时将 skipNegotiation
设置为 true
解决了
this.connection = new HubConnectionBuilder()
.withUrl(`${environment.baseUrl}/hubs/wechat-mp-auth`, {
skipNegotiation: true,
transport: HttpTransportType.WebSockets
})
.build();
Negotiation 需要用到粘滞会话(Sticky Sessions),而我们使用的阿里云传统型负载均衡 CLB 不支持 Sticky Sessions
参考: