【问题标题】:Connect signalr with vue / vuex用 vue / vuex 连接信号器
【发布时间】: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

标签: vue.js signalr vuex


【解决方案1】:

切换到 .core 对象。

在“配置”下

app.UseCors(builder => builder.WithOrigins("http://localhost:8080").AllowAnyMethod().AllowAnyHeader().AllowCredentials());

app.UseSignalR(route => {route.MapHub<UserHub>("/user-hub");} );

在 配置服务

services.AddSignalR();
services.AddCors();

在vue组件(ts)

created: function() {
    this.$userHub.$on("user-added-event", this.userAddedEvent);
  },
  beforeDestroy: function() {
    //clean SignalR event
    this.$userHub.$off("user-added-event", this.userAddedEvent);
  },

user-hub.js 用于处理连接。 作为 vue 插件导入

import { HubConnectionBuilder, LogLevel } from "@aspnet/signalr";
export default {
  install(Vue) {

    const connection = new HubConnectionBuilder()
      .withUrl(`${Vue.prototype.$http.defaults.baseURL}/user-hub`) 
      .configureLogging(LogLevel.Information)
      .build();


    const userHub = new Vue();

    Vue.prototype.$userHub = userHub;

    connection.on("AddUserEvent", (userId, userName) => {
      userHub.$emit("user-added-event", { userId, userName });
    });

    // if connection closed, reopen it
    let startedPromise = null;
    function start() {
      startedPromise = connection.start().catch(err => {
        return new Promise((resolve, reject) =>
          setTimeout(
            () =>
              start()
                .then(resolve)
                .catch(reject),
            5000
          )
        );
      });
      return startedPromise;
    }

    connection.onclose(() => start());

    start();
  }
};

完整的项目将被上传到 git。

【讨论】:

    猜你喜欢
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多