Using SignalR for my server and Angular for my client... When I run my client I receive these errors:
zone.js:2969 OPTIONS https://localhost:27967/chat/negotiate 0 ()
Utils.js:148 Error: Failed to complete negotiation with the server: Error
Utils.js:148 Error: Failed to start the connection: Error
I am guessing it is something with CORS... I am trying to implement a simple chat application. I am using the latest verison of SignalR:
Here is the github that contains the code for the tutorial I am following. SignalR Chat Tutorial
Here is my startup
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace signalrChat
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder
.AllowAnyMethod()
.AllowAnyHeader()
.WithOrigins("http://localhost:4200");
}));
services.AddSignalR();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("CorsPolicy");
app.UseSignalR(routes =>
{
routes.MapHub<ChatHub>("/chat");
});
}
}
}
And here is my client:
import { Component, OnInit } from '@angular/core';
import { HubConnection, HubConnectionBuilder } from '@aspnet/signalr';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
private hubConnection: HubConnection;
nick = '';
message = '';
messages: string[] = [];
ngOnInit() {
this.nick = window.prompt('Your name:', 'John');
this.hubConnection = new HubConnectionBuilder().withUrl('https://localhost:27967/chat').build();
this.hubConnection
.start()
.then(() => console.log("Connection Started!"))
.catch(err => console.log("Error while establishing a connection :( "));
this.hubConnection.on('sendToAll', (nick: string, receiveMessage: string) => {
const text = `${nick}: ${receiveMessage}`;
this.messages.push(text);
})
}
public sendMessage(): void {
this.hubConnection
.invoke('sendToAll', this.nick, this.message)
.catch(err => console.log(err));
}
}
I assume it may be something with cors. Thank you!
EDIT: I just recreated the signalr implementation in visual studio and it worked. I believe I chose the wrong settings on start up.
connection = new signalR.HubConnectionBuilder()
.configureLogging(signalR.LogLevel.Debug)
.withUrl("http://localhost:5000/decisionHub", {
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets
})
.build();
I faced the slimier issue and I fixed it by adding
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets
in client-side as @Caims mentioned. But I don't think this is the correct solution and feel more like a hack 😊.
What you have to do is adding AllowCredentials
in server side. Anyway when it's coming to Azure you can't relay on that fix. So no need enable WSS only in client side.
Here is my ConfigureServices method:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("CorsPolicy", builder => {
builder
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
.WithOrigins("http://localhost:4200");
}));
services.AddSignalR();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
This is my Configure method:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("CorsPolicy");
app.UseSignalR(routes =>
{
routes.MapHub<NotifyHub>("/notify");
});
app.UseMvc();
}
And finally this is how I connected from client-side:
const connection = new signalR.HubConnectionBuilder()
.configureLogging(signalR.LogLevel.Debug)
.withUrl("http://localhost:5000/notify", {
//skipNegotiation: true,
//transport: signalR.HttpTransportType.WebSockets
}).build();
connection.start().then(function () {
console.log('Connected!');
}).catch(function (err) {
return console.error(err.toString());
});
connection.on("BroadcastMessage", (type: string, payload: string) => {
this.msgs.push({ severity: type, summary: payload });
});
I had the same problem, and it turns out that the launchSettings.json in the part where it says signalRchatServer does nothing, the url that worked with me was that of the iisexpress, I say it because there are many places where they say that the url is the one below .
I was pointing to the wrong endpoint. I was using
https://localhost:5001/api/message-hub
instead of
https://localhost:5001/message-hub
(extra /api)
Also if you're using Angular, you're likely to get a Websocket not OPEN error right after fixing this one, so here's a link to save you from more searches.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With