.net 6:无法从 Vuejs 连接到 signalR
.net 6: can not connect from Vuejs to signalR
我看了很多教程,我遵循教程格式,但是我的项目失败了。
请看我的代码:
在 vs 代码中,我的 vue.js 项目:
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
})
}
对比 2022 年:我的中心项目:
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);
}
}
}
但结果:
result image
将这些代码添加到 program.cs:
builder.Services.AddCors(options =>
{
options.AddPolicy(name: "MyPolicy",
builder =>
{
builder.WithOrigins(
"http://localhost:8081")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
And
app.UseCors("MyPolicy");
我看了很多教程,我遵循教程格式,但是我的项目失败了。
请看我的代码:
在 vs 代码中,我的 vue.js 项目:
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 }) }
对比 2022 年:我的中心项目:
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); } } }
但结果: result image
将这些代码添加到 program.cs:
builder.Services.AddCors(options => { options.AddPolicy(name: "MyPolicy", builder => { builder.WithOrigins( "http://localhost:8081") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); });
And
app.UseCors("MyPolicy");