React Native中Pusher私有频道onAuthorization方法无法正常工作
以下是针对问题的具体排查和修复步骤:
1. 填充有效API密钥
你的代码中apiKey字段为空,私有频道认证依赖有效的Pusher应用密钥,必须填入对应项目的API密钥才能触发授权流程。
2. 修正onAuthorizer函数的返回值要求
Pusher的onAuthorizer必须返回包含授权信息的对象(或Promise),仅打印日志会导致授权流程中断。需要调用后端接口获取合法的授权签名,示例如下:
onAuthorizer: async (channelName, socketId) => { console.warn(channelName, socketId); // 调用后端授权接口 try { const response = await fetch('你的后端授权接口地址', { method: 'POST', headers: { 'Content-Type': 'application/json', // 按需添加用户身份认证头,比如Bearer Token 'Authorization': `Bearer ${用户token}` }, body: JSON.stringify({ socket_id: socketId, channel_name: channelName }) }); const authData = await response.json(); // 返回Pusher要求的授权结构 return { authorization: authData.authorization }; } catch (error) { console.error('授权请求失败:', error); throw error; } }
3. 修复onError函数的语法错误
原代码中$message是语法错误,修正后可正确输出错误日志,帮助定位问题:
onError(message, code, e) { console.log(`onError: message: ${message} code: ${code} exception: ${e}`); }
4. 确保频道命名规范
私有频道必须以private-为前缀,你的private-my-channel符合规范,但需同步确认后端授权逻辑对该频道名的处理正确。
修正后的完整代码示例
useEffect(() => { getConnectToPusher(); }, []); const getConnectToPusher = async () => { console.log('Calling'); const pusher = Pusher.getInstance(); await pusher.init({ apiKey: '你的有效Pusher API密钥', cluster: 'ap1', onAuthorizer: async (channelName, socketId) => { console.warn(channelName, socketId); try { const response = await fetch('https://your-backend-api/pusher-auth', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${用户身份token}` }, body: JSON.stringify({ socket_id: socketId, channel_name: channelName }) }); const authData = await response.json(); return { authorization: authData.authorization }; } catch (error) { console.error('授权请求失败:', error); throw error; } }, onError(message, code, e) { console.log(`onError: message: ${message} code: ${code} exception: ${e}`); } }); await pusher.connect(); const myChannel = await pusher.subscribe({ channelName: 'private-my-channel', onSubscriptionSucceeded: (channelName, data) => { console.log(`Subscribed to ${channelName}`); console.log(`I can now access me: ${JSON.stringify(myChannel.me)}`); console.log(`And here are the channel members: ${JSON.stringify(myChannel.members)}`); }, onEvent: (event) => { console.log(`Event received: ${JSON.stringify(event)}`); }, }); }
内容的提问来源于stack exchange,提问作者Jaman shuvo
相关产品推荐
相关产品推荐

