skip to Main Content

Based on the official documentation, i am able to get the subscribed messages. When i simply run the javascript code, it runs without any error.


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();

But when i try to do this within React class’s, componentDidMount() function, facing error.

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

Stacktrace 1
Stack Trace 1

Stacktrace 2
Stacktrace 2

Stacktrace 3
Stacktrace 3

2

Answers


  1. Chosen as BEST ANSWER

    Azure support team has added the sample react example which can be found in this link https://github.com/Azure/azure-webpubsub/tree/main/samples/javascript/chatapp/react .

    Required react libraries are,

    "@azure/web-pubsub": "^1.1.1",
    "@azure/web-pubsub-client": "^1.0.0-beta.3",
    

    Based on the above response, i have created a sample app which has python flask as backend and react as front end

    https://github.com/Nandha1712/azure_pubsub_react_example


    • The issue here is with the Jsonwebtoken package which is used with the websocket.

    • Jsonwebtoken is predominantly build for NodeJS to be run on a web server so it doesn’t fully work with the client-side rendering of the react apps

    • try installing the latest version of jsonwebtoken , otherwise the ideal way of working would be with an intermediary between the react app and azure pub sub.

    • One workaround with this approach would be with azure function with azure web pub sub input/output bindings. and then use a WebSocket in the react app to connect to the azure function.

    • Here you will need a HTTP trigger with the input bindings of the azure pub sub . This trigger will return the URL which you can use in web sockets of your react app.

    function.json (for http trigger) :

    {
    "bindings":[
                {
                    "authLevel": "anonymous",
                    "type": "httpTrigger",
                    "direction": "in",
                    "name": "req"
                },
                {
                    "type": "http", 
                    "direction": "out",
                    "name": "res"
                },
                {
                    "type": "webPubSubConnection",
                    "name": "connection",
                    "hub": "notification",
                    "direction": "in"
                }
        ]
    }
    
    • Here I am sending the message using a time trigger and in a simple HTML file I created a WebSocket the html file which is served using different HTTP trigger. Thus after every interval of time I will get messages

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search