【发布时间】:2020-05-09 17:26:21
【问题描述】:
我正在尝试将 SignalR 集线器连接到 Vue 组件,但我没有这样做。我用谷歌搜索了“vue with signalr”,几乎每个链接都到了第二页。 我得到了一个 cors 起源,但我不认为这是主要问题,因为我对 web api 的 post/get 调用运行良好。 c#端口号63213,客户端8080
我也在使用 vuex,我想知道我是否应该在商店连接。 这是代码示例。我使用带有 typescript falvor 的 vue/vuex。
mounted: function() {
//... under mounted, signalR connection. i am using import * as signalR from "@aspnet/signalr";
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl("http://localhost:63213/ChatHub")
.build();
// connecting to the hub
this.hubConnection
.start()
.then(() => console.log("connection started"))
.catch(err => console.log("connecting hub failed err is : ", err));
//at the hub there is a function named broadcastMessage, should return string that will be added to an array. should it be at sotr's getter
this.connection.on("broadcastMessage", function(msg: string) {
this.messages.push({ msg });
});
},
c#
public class Startup
{
public void Configuration(IAppBuilder app)
{
var policy = new CorsPolicy()
{
AllowAnyOrigin = true,
AllowAnyHeader = true,
AllowAnyMethod = true,
SupportsCredentials = true
};
policy.Origins.Add("http://localhost:8080");
// Any connection or hub wire up and configuration should go here
app.MapSignalR();
}
}
- pot get to web api 运行良好。
枢纽
public class ChatHub : Hub
{
public static void SendMessage(string msg)
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
hubContext.Clients.All.broadcastMessage(msg, " !! !! ");
}
}
错误是:
从源“http://localhost:8080”访问“http://localhost:63213/ChatHub/negotiate”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头出现在请求的资源上。
我应该将集线器连接传递给商店吗? 我做错了什么?
谢谢。
【问题讨论】:
-
问题解决了,我会用 TS falvor 上传完整的解决方案。使用 .netCore