基于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
最佳答案
此处的问题在于与
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 触发器提供服务。因此,每隔一段时间我就会收到消息
关于javascript - 从 React 订阅 Azure Pub Sub Web 服务会导致未处理的拒绝(TypeError),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75435687/