Home > database >  .net 6: can not connect from Vuejs to signalR
.net 6: can not connect from Vuejs to signalR

Time:12-04

I see a lot of tutorial and I follow tutorial format, but my project failded.
please see my codes:
in vs code, my vue.js project:

main.js:

import VueSignalR from '@latelier/vue-signalr'
Vue.use(VueSignalR, 'https://localhost:7082/chathub')

test.vue:

created () {
  this.$socket.start({
    log: true // Logging is optional but very helpful during development
  })
}

in vs 2022: my hub project:

program.cs:

using WebApp2;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSignalR();
var app = builder.Build();

app.MapGet("/", () => "Hello World!");
app.UseRouting();
app.UseEndpoints(endpoints =>
{
    endpoints.MapHub<ChatHub>("/chathub");
});

app.Run();

hub.cs:

using Microsoft.AspNetCore.SignalR;

namespace WebApp2
{
    public class ChatHub : Hub
    {
        public Task SendMessage(string user, string message)
        {
            return Clients.All.SendAsync("ReceiveMessage", user, message);
        }
    }
}

but result: result image

CodePudding user response:

add these code to program.cs:

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: "MyPolicy",
                builder =>
                {
                    builder.WithOrigins(
                        "http://localhost:8081")
                            .AllowAnyHeader()
                            .AllowAnyMethod()
                            .AllowCredentials();
                });
});

And
app.UseCors("MyPolicy");

  • Related