基于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;
×未经处理的拒绝(类型错误):“instanceof”的右侧不是对象
堆栈跟踪1
堆栈跟踪2
堆栈跟踪3
1条答案
按热度按时间hm2xizp91#
websocket
一起使用的Jsonwebtoken
软件包有关。Jsonwebtoken
主要是为运行在Web服务器上的NodeJS构建的,因此它不能完全用于react应用程序的客户端呈现jsonwebtoken
,否则理想的工作方式是在react应用程序和azure pubsub之间使用一个中介。函数. json(用于http触发器):