Подключите сигнализатор с vue / vuex - PullRequest
0 голосов
/ 23 января 2020

Я пытаюсь подключить концентратор SignalR к Vue компоненту, но мне не удается это сделать. я погуглил "vue с сигнализатором" и реал почти каждую ссылку до второй страницы. Я получаю cors origin, но я не думаю, что это главная проблема, так как мой post / get вызов web api работает хорошо. c# номер порта 63213, клиент на 8080

Я также использую vuex, и мне интересно, если я должен подключиться в магазине. Вот примеры кода. Я использую 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 to web api работают хорошо.

hub

public class ChatHub : Hub
    {

        public static void SendMessage(string msg)
        {
            var hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
            hubContext.Clients.All.broadcastMessage(msg, " !! !! ");
        }
    }

ошибка:

Доступ к XMLHttpRequest по адресу http://localhost: 63213 / ChatHub /gotiate 'от источника' http://localhost : 8080 'было заблокировано политикой CORS: Ответ на запрос предварительной проверки не проходит проверку контроля доступа: в запрошенном ресурсе отсутствует заголовок «Access-Control-Allow-Origin».

я передаю хаб в магазин? что я делаю не так?

спасибо.

1 Ответ

0 голосов
/ 29 января 2020

переключено на объект .core.

в разделе "Настройка"

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

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

в разделе ConfigureServices

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.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...