【问题标题】:Unexpected error in Pusher private channel subscriptionPusher 私人频道订阅出现意外错误
【发布时间】:2019-02-03 07:55:26
【问题描述】:

在 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');

我的授权码被调用并返回一个有效的授权签名:

{\"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 文档中找不到任何提及此问题的内容。有人看到过这个,或者有解决方法的想法吗?

【问题讨论】:

    标签: javascript php pusher subscribe


    【解决方案1】:

    此错误的最可能原因是 auth 哈希在从服务器返回之前已“字符串化”。这就是为什么错误消息提到发现了一个无效的键:无法将值解析为 JSON 对象。

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

    【讨论】:

      【解决方案2】:

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

      $thePusher = new \Pusher\Pusher(
         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);
      

      【讨论】:

      • 为了避免JSON的解码和重新编码,我们可以return response($theResult, 200)->header('Content-Type', 'application/json');
      猜你喜欢
      • 2014-07-15
      • 2015-06-05
      • 2017-05-12
      • 2017-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-22
      • 1970-01-01
      相关资源
      最近更新 更多