javascript - 从 React 订阅 Azure Pub Sub Web 服务会导致未处理的拒绝(TypeError)

标签 javascript reactjs azure websocket azure-pubsub

基于official documentation ,我能够获取订阅的消息。当我简单地运行 JavaScript 代码时,它运行时没有任何错误。


const WebSocket = require('ws');
const { WebPubSubServiceClient } = require('@azure/web-pubsub');

async function main() {
  const hub = "hub1";
  let service = new WebPubSubServiceClient(process.env.WebPubSubConnectionString, hub);
  let token = await service.getClientAccessToken();
  let ws = new WebSocket(token.url);
  ws.on('open', () => console.log('connected'));
  ws.on('message', data => console.log('Message received: %s', data));
}

main();

但是当我尝试在 React 类中执行此操作时,componentDidMount() 函数遇到错误。

import React from "react";

// == Azure WebPuSub
// import { WebPubSubServiceClient } from '@azure/web-pubsub';
// import { WebSocket } from 'ws';
const { WebPubSubServiceClient } = require('@azure/web-pubsub');
const WebSocket = require('ws');


class AzurePubSubTest extends React.Component {

    constructor(_props, _context) {
        super(_props, _context);
        this.connectToPubSub = this.connectToPubSub.bind(this);
        this.state = {
        }
    }

    async componentDidMount() {
        console.log("===Mounting....")
        await this.connectToPubSub();
    }

    componentWillUnmount() {
        console.log("Unmounting....")
    }

    async connectToPubSub() {
        const hub = "hub1";
        let endpoint;
        // endpoint = process.env.WebPubSubConnectionString;
        endpoint = "Endpoint=https://***check.webpubsub.azure.com;AccessKey=***;Version=1.0;"
        // endpoint = "wss://***check.webpubsub.azure.com/client/hubs/Hub?access_token=***"; 
        console.log("process.env.WebPubSubConnectionString");
        console.log(endpoint);

        let service = new WebPubSubServiceClient(endpoint, hub);
        let token = await service.getClientAccessToken();
        let ws = new WebSocket(token.url);
        ws.on('open', () => console.log('connected'));
        ws.on('message', data => console.log('Message received: %s', data));

    }

    render() {
        const user = { username: "Check" };
        let testMessages = [];
        if (testMessages === undefined || testMessages === null) {
            testMessages = [];
        }

        return (
            <div>Testing....</div>
        )
    }
}


export default AzurePubSubTest;

× Unhandled Rejection (TypeError): Right-hand side of 'instanceof' is not an object

堆栈跟踪 1 Stack Trace 1

堆栈跟踪 2 Stacktrace 2

堆栈跟踪 3 Stacktrace 3

最佳答案

  • 此处的问题在于与 websocket 一起使用的 Jsonwebtoken 包。

  • Jsonwebtoken 主要是为在 Web 服务器上运行的 NodeJS 构建的,因此它不能完全与 React 应用程序的客户端渲染配合使用

  • 尝试安装最新版本的 jsonwebtoken ,否则理想的工作方式是在 React 应用程序和 azure pub sub 之间使用中介。

  • 此方法的一个解决方法是使用 azure 函数和 azure web pub sub 输入/输出绑定(bind)。然后在react应用程序中使用WebSocket连接到azure函数。

  • 这里您需要一个带有 azure pub sub 的输入绑定(bind)的 HTTP 触发器。此触发器将返回您可以在 React 应用程序的 Web 套接字中使用的 URL。

function.json(用于http触发器):

{
"bindings":[
            {
                "authLevel": "anonymous",
                "type": "httpTrigger",
                "direction": "in",
                "name": "req"
            },
            {
                "type": "http", 
                "direction": "out",
                "name": "res"
            },
            {
                "type": "webPubSubConnection",
                "name": "connection",
                "hub": "notification",
                "direction": "in"
            }
    ]
}
  • 在这里,我使用时间触发器发送消息,并在一个简单的 HTML 文件中创建了一个 WebSocket,该 html 文件使用不同的 HTTP 触发器提供服务。因此,每隔一段时间我就会收到消息

enter image description here

关于javascript - 从 React 订阅 Azure Pub Sub Web 服务会导致未处理的拒绝(TypeError),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75435687/

相关文章:

javascript - 调用覆盖的 .click() 方法

javascript - jQuery-获取所有超链接图像

javascript - OAuth2,使用 POST 但...方法不允许?

javascript - 在 JS canvas 中绘制正弦波不执行任何操作

azure - 在 AAD 应用程序注册中显示与托管服务身份服务主体关联的应用程序

javascript - Angular 9按钮点击多次

reactjs - 使用渲染外部的堆栈导航访问 channel 数据

javascript - 如何在 React 中使用 Material UI 定义背景图像来填充屏幕并删除左侧和右侧的边缘?

c# - Azure移动服务: publish throwing error VS 2013

java - 使用 REST API 将 block Blob 列表放在 Azure 存储上时,指定的 XML 在语法上无效错误