如何将连接时Websocket参数从Elm传递给Phoenix? [英] How do I pass connection-time websocket parameters to Phoenix from Elm?

查看:184
本文介绍了如何将连接时Websocket参数从Elm传递给Phoenix?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直沿 对Phoenix编程 ,但使用了Elm是我的前端,而不是Javascript.该书的第二部分描述了如何使用websocket.本书的运行示例为您创建了一个身份验证令牌,供客户端在连接创建时传递给Phoenix. Phoenix提供的Javascript Socket类允许这样做,但是Elm中没有明显的方法可以做到这一点(从0.17开始,并且是这个问题的发布日期).

I was following along Programming Phoenix but using Elm for my front end, rather than Javascript. The second part of that book describes how to use websockets. The book's running example has you create an authentication token for the client side to pass to Phoenix at connection creation time. The Javascript Socket class provided with Phoenix allows that, but there's no obvious way to do it in Elm (as of 0.17 and the date of this question).

推荐答案

  1. 就像在书中一样,通过将令牌附加到window,使令牌对Java可见.

  1. As in the book, make the token visible to Javascript by attaching it to window.

<script>window.auth_token = "<%= assigns[:auth_token] %>"</script>

  • web/static/js/app.js中,您将具有启动Elm的代码.将令牌传递到那里.

  • In web/static/js/app.js, you'll have code that starts Elm. Pass the token there.

    const c4uDiv = document.querySelector('#c4u-target');
    if (c4uDiv) {
      Elm.C4u.embed(c4uDiv, {authToken: window.auth_token});
    }
    

  • 在榆木方面,您将使用programWithFlags而不是program.
  • 您的init函数将带有flags参数. (我将导航库用于单个-页面应用程序,这也是为什么还有一个PageChoice参数的原因.)

  • On the Elm side, you'll use programWithFlags instead of program.
  • Your init function will take a flags argument. (I'm using the Navigation library for a single-page app, which is why there's a PageChoice argument as well.)

    type alias Flags =
      { authToken : String
      }
    
    init : Flags -> MyNav.PageChoice -> ( Model, Cmd Msg )
    

  • init内,将标记作为URI查询对添加.请注意,您必须使用uri编码,因为令牌包含奇数字符.这是执行此操作的粗略方法.注意:我正在使用 elm-phoenix-socket 下面的库,但是其他人也需要使用相同的黑客工具.

  • Within init, tack on the token as a URI query pair. Note that you have to uri-encode because the token contains odd characters. Here's the crude way to do that. Note: I am using the elm-phoenix-socket library below, but the same hackery would be required with others.

      let
        uri = "ws://localhost:4000/socket/websocket?auth_token=" ++
              (Http.uriEncode flags.authToken)
      in
        uri
        |> Phoenix.Socket.init
        |> Phoenix.Socket.withDebug
        |> Phoenix.Socket.on "ping" "c4u" ReceiveMessage
    

  • 这篇关于如何将连接时Websocket参数从Elm传递给Phoenix?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆