在我的应用程序中,我有几个像这样使用 signalR 的屏幕。该函数称为 useEffect 函数,它的工作原理是:
const setupSignalR = () =>
{
SecureStore.getItemAsync("token").then(tk => {
let connection = new HubConnectionBuilder()
.withUrl("URL", {
accessTokenFactory: () => tk
})
.build();
connection.on("Update", function (message) {
//DOSTUFF
});
connection.start()
.then(() => console.log("connection started"))
.catch(err => console.log("connecting hub failed err is : ", err));
});
}
Run Code Online (Sandbox Code Playgroud)
问题是,如果我离开屏幕,连接将保持打开状态,当我返回屏幕时,我会打开另一个连接,这意味着我现在同时打开了 2 个连接。我知道 signalR 有一个可以调用的停止函数,所以我尝试使用这样的导航侦听器,但它们没有被调用:
useEffect(() =>
{
Load();
setupSignalR();
const unsubscribe = navigation.addListener('focus', () => {
});
const sub = navigation.addListener('blur', () => {
console.log("============");
});
}, [navigation]);
Run Code Online (Sandbox Code Playgroud)
我通常通过按后退按钮或使用 …
我目前正在学习这个基本信号 R 教程。但因为我想在现有项目中使用它,所以我将其分开。中心与客户端位于不同的项目内。因此IP地址不同。在 Hub I 的配置中当然启用了 cors:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers();
services.AddSignalR();
//other configuration code
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env){
app.UseRouting();
app.UseCors(x => x
.AllowAnyMethod()
.AllowAnyHeader()
.AllowAnyOrigin()
);
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<LiveUpdating.ChatHub>("/chatHub");
});
}
Run Code Online (Sandbox Code Playgroud)
但是,当我现在尝试连接到客户端中的 chatHub(设置与上面的链接完全相同,只是我将连接更改为var connection = new signalR.HubConnectionBuilder().withUrl("https://localhost:44316/chatHub").build();
)时,我收到此错误:
Access to fetch at 'https://localhost:44316/chatHub/negotiate?negotiateVersion=1' from
origin 'https://localhost:44341' has been blocked by CORS policy: Response to preflight
request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin'
header in …
Run Code Online (Sandbox Code Playgroud)