Trying to write Hub in my server to broadcast notifications to clients
In my Server: 1 - Installed the nuget. 2 - Created Startup.cs with app.MapSignalR(); 3 - Created hub:
[HubName("NotificationHub")]
public class NotificationHub : Hub
{
// required to let the Hub to be called from other server-side classes/controllers, using static methods
private static IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
// Send the data to all clients (may be called from client JS)
public void GetNotifications()
{
Clients.All.GetNotifications();
}
// Send the data to all clients (may be called from server C#)
public static void GetNotificationsStatic()
{
hubContext.Clients.All.GetNotifications();
}
}
4 - Created controller with Get and Add notifications.
In my client: followed this guide: https://medium.com/@ghanshyamshukla/implementation-of-signalr-in-angular-5-app-with-asp-net-web-api-2-0-f09672817d4d (in my angular.json instead of '../node_modules..' I've fixed to './node_modules..'
and this is my connection function:
connectToSignalRHub() {
const signalRServerEndPoint = environment.baseURL;
this.connection = $.hubConnection(signalRServerEndPoint);
this.proxy = this.connection.createHubProxy('notificationHub');
this.proxy.on('messageReceived', () => {
console.log('new notifications');
});
this.connection.start().done((data: any) => {
console.log('Connected to Notification Hub');
}).catch((error: any) => {
console.log('Notification Hub error -> ' + error);
});
}
Then when I run my app,
when trying to connect with this.connection.start()
I get to the error section with error:
Error: Error during negotiation request. at Object.error (jquery.signalR.min.js:9)
and I see in my console this error:
Access to XMLHttpRequest at 'https://localhost:44328/signalr/negotiate?clientProtocol=2.1&connectionData=%5B%7B%22name%22%3A%22notificationhub%22%7D%5D&_=1563949114481' from origin 'http://localhost:8083' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Needless to say I've enabled CORS for my app
OPTIONS
request to'https://localhost:44328/signalr/negotiate?clientProtocol=2.1&connectionData=%5B%7B%22name%22%3A%22notificationhub%22%7D%5D&_=1563949114481
and show us response headers – vasily.sib