无法完成与服务器的协商-Angular + SignalR

时间:2020-06-12 18:10:18

标签: javascript node.js angular azure azure-signalr

我无法使用Nodejs使用Angular + Azure Functions建立连接。我知道后端有效,因为我使用以下documentation创建了后端,并使用docs中提供的客户端URL对其进行了测试。消息正在跨多个客户端工作。

所以现在我正在尝试使Angular工作。我已经在Angular中为Signalr创建了一个服务来建立连接,但是我遇到了错误

enter image description here enter image description here

并在“网络”标签上

enter image description here 我还尝试在服务中替换此代码


  private buildConnection = () => {
    this.hubConnection = new signalR.HubConnectionBuilder()
      .withUrl("http://localhost:7070") //use your api adress here and make sure you use right hub name.
      .build();
  };

使用此代码

  private buildConnection = () => {
    this.hubConnection = new signalR.HubConnectionBuilder()
      .configureLogging(signalR.LogLevel.Debug)
      .withUrl("http://localhost:7070/api", {
        skipNegotiation: true,
        transport: signalR.HttpTransportType.WebSockets
      })
      .build();

根据此post的建议答案,然后返回

enter image description here

我之前从未使用过SignalR,所以我试图通过阅读一些教程来将其组合在一起。感谢您的帮助!

信号服务

import { Injectable, EventEmitter } from "@angular/core";
import * as signalR from "@aspnet/signalr";
import { SignalViewModel } from "./signal-view-model";

@Injectable({
  providedIn: "root"
})
export class SignalRService {
  private hubConnection: signalR.HubConnection;
  signalReceived = new EventEmitter<SignalViewModel>();

  constructor() {
    this.buildConnection();
    this.startConnection();
  }

  private buildConnection = () => {
    this.hubConnection = new signalR.HubConnectionBuilder()
      .withUrl("http://localhost:7070/api") //c
      .build();
  };

  private startConnection = () => {
    this.hubConnection
      .start()
      .then(() => {
        console.log("Connection Started...");
        this.registerSignalEvents();
      })
      .catch(err => {
        console.log("Error while starting connection: " + err);

        //if you get error try to start connection again after 3 seconds.
        setTimeout(function () {
          this.startConnection();
        }, 3000);
      });
  };

  private registerSignalEvents() {
    this.hubConnection.on("SignalMessageReceived", (data: SignalViewModel) => {
      this.signalReceived.emit(data);
    });
  }
}

就像上面的Reference Docs链接一样,这就是我的azure函数的样子

消息


module.exports = async function (context, req) {
  return {
    "target": "newMessage",
    "arguments": [ req.body ]
  };
};

谈判


module.exports = async function (context, req, connectionInfo) {
  context.res.json(connectionInfo);
};

host.json

{
  "version": "2.0",
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[1.*, 2.0.0)"
  },
  "Host": {
    "LocalHttpPort": 7070,
    "CORS": "http://localhost:4200",
    "CORSCredentials": true
  }
}

1 个答案:

答案 0 :(得分:1)

好吧,因为de CORS政体,您无法将Angular与SignalR功能连接。

您忘记在功能上配置CORS。 enter image description here

尝试使用此配置。