SignalR - ошибка connection.start - PullRequest
       32

SignalR - ошибка connection.start

0 голосов
/ 20 ноября 2018

Я пытаюсь запустить учебник из Энтони Чу .https://www.youtube.com/watch?v=4d0wor7uAgQ

Он реализовал «SimpleChat-приложение» с Azure CosmosDB, функциями Azure и SignalR.Где вы можете отправлять сообщения между клиентами в режиме реального времени.Я пробовал разные настройки и версию, но я не могу заставить ее работать.

Исходный код в моем "index.html": (JavaScript)

  <script src="https://unpkg.com/@aspnet/signalr@1.0.0-rc1-final/dist/browser/signalr.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

  <script>
    const apiBaseUrl = 'http://localhost:7071';
    const hubName = 'chat';
    getConnectionInfo().then(info => {      
      let username;
      while (!username && username !== null) {
        username = prompt('Enter a username');
      }
      console.log(info.accessTokenFactory);
      if (username === null) return;
      document.body.classList.add('ready');
      const messageForm = document.getElementById('message-form');
      const messageBox = document.getElementById('message-box');
      const messages = document.getElementById('messages');
      const options = {
        accessTokenFactory: () => info.accessKey
      };

      const connection = new signalR.HubConnectionBuilder()
        .withUrl(info.url, options)
        .configureLogging(signalR.LogLevel.Trace)
        .build();

      connection.onclose(() => console.log('disconnected'));

      console.log('retrieving messages');

      getMessage().then(messages => {
        for(let m of messages) {
          newMessage(m);
        }
        console.log('connecting...');
        connection.start()
          .then(() => console.log('connected!'))
          .catch(console.error);
      });
      console.log('connected after');
    }).catch(alert);

    function getConnectionInfo() {
      console.log("test");
      return axios.post(`${apiBaseUrl}/api/negotiate`)
        .then(resp => resp.data);
    }

    function getMessage(sender, messageText) {
      return axios.get(`${apiBaseUrl}/api/getmessage`).then(resp => resp.data);
    }

    function newMessage(message) {
      const newMessage = document.createElement('li');
      newMessage.appendChild(document.createTextNode(`${message.sender}: ${message.text}`));
      messages.prepend(newMessage);
    }
  </script>

Исходный код (согласование - function.json)

{
  "disabled": false,
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    },
    {
      "type": "signalRConnectionInfo",
      "name": "connectionInfo",
      "hubName": "chat",
      "connectionStringSetting": "AzureSignalRConnectionString", 
      "direction": "in"
    }
  ]
}

Исходный код (согласование - index.js)

module.exports = function (context, req, connectionInfo) {
    context.res = { body: connectionInfo };
    context.done();
}

Я могу получитьданные из cosmosDB, но когда я прихожу к методу connection.start () ... он не подключается к службе?!

Кто-нибудь может мне помочь?

Большое спасибо !!!

Версии:

  • Func (2.2.70)

  • Microsoft.Azure.WebJobs.Extensions.SignalRService (1.0.0-preview1-10002)

  • Microsoft.Azure.WebJobs.Extensions.CosmosDB (3.0.2)

  • Microsoft.Azure.WebJobs.Script.ExtensionsMetadataGenerator (1.0.1)

(«Me: Hallo» - это запись в CosmosDB)

РезультатСтраница с Console-Log

1 Ответ

0 голосов
/ 21 ноября 2018

Позаботьтесь в этом разделе кода ...

      const options = {
        accessTokenFactory: () => info.accessKey
      };

      const connection = new signalR.HubConnectionBuilder()
        .withUrl(info.url, options)
        .configureLogging(signalR.LogLevel.Trace)
        .build();

измените

=> info.accessKey

и вставьте

=> info.accessToken

Не удалось установить соединение из-за неопределенного значения!

...