推送器专用频道订阅中出现意外错误



在JS+PHP(宅基地)环境中,在Pusher中订阅公共频道工作正常(也验证我的凭据)。订阅专用频道失败,给定以下代码:

 let theAppId = 'XXXYYYZZZ'; //fake credentials shown here...
 pusher = new Pusher(theAppId, {
    authEndpoint: '/pusher/auth',
    cluster: 'us2',
    forceTLS: true,
    encrypted: true,
    auth: {headers: {'X-CSRF-Token': self.csrf}}
});
channel = pusher.subscribe('private-channel1');

我的身份验证代码被调用并返回有效的身份验证 sig:

{"auth":"c289b20c368bd23a4a85:d55f1f1495f0d252b5fde1d69e2e6d5b4b161ca49cab5ad218d65111ae307a12"}"}

连接成功后,Pusher.log显示此错误:

Pusher : Event recd : {"event":"pusher:error","data":{"code":null,"message":"Invalid key in subscription auth data: '{"auth"'"}}
pusher.min.js:8 Pusher : Error : {"type":"WebSocketError","error":{"type":"PusherError","data":{"code":null,"message":"Invalid key in subscription auth data: '{"auth"'"}}}

我在 Pusher 文档中找不到任何关于这个问题的提及。有人看到过这个,或者对如何解决有想法吗?

此错误最可能的原因是auth哈希在从服务器返回之前被"字符串化"。这就是错误消息提到找到无效键的原因:无法将该值解析为 JSON 对象。

若要解决此问题,服务器需要返回纯 JSON。

感谢霍萨姆的提示。对于Laravel用户来说,这个问题很容易解决。请注意,来自身份验证路由的响应是 json。从pusher->socket_auth创建有效身份验证密钥返回的值是 json 编码的字符串。要解决此问题,只需将socket_auth响应json_decode到关联数组,然后将其传递到控制器 json 响应中:

$thePusher = new PusherPusher(
   env('PUSHER_APP_KEY'),env('PUSHER_APP_SECRET'),env('PUSHER_APP_ID'),
      ['cluster'=>env('PUSHER_CLUSTER'),'useTLS'=>true]
);
$theResult=$thePusher->socket_auth(
   $aRequest>input('channel_name'),
   $aRequest->input('socket_id'));
return response()->json(json_decode($theResult,true),200);

最新更新