gpt4 book ai didi

cookies - 如何在Elm中读取cookie?

转载 作者:行者123 更新时间:2023-12-02 01:51:40 24 4
gpt4 key购买 nike

我在this SO question中学到了目前没有简单的方法可以将基于 cookie 的 CSRF token 转换为 Elm 中的 HTTP 请求 header 。因此,要编写一个与 Django Rest Framework 后端完美配合的单页应用程序 (SPA),我需要从相应的 cookie 值中手动检索 CSRF-Token。

如何在 Elm 中检索 cookie 值? Elm 是否通过某些命令为此提供运行时支持?或者我是否需要使用纯 JavaScript 检索 cookie 并通过端口将其提供给 ELM SPA?

最佳答案

从 Elm 0.9 开始,您需要使用 Ports从 JavaScript 读取 cookie 并将其传回 Elm 应用程序。

在我的应用程序中,我执行以下操作。我定义了一个 fetchCsrfToken 端口,使用 Elm 来调用读取 cookie 的 JavaScript 函数。然后,该函数通过 csrfTokenReciever 端口触发对 Elm 的回调。我的 Elm 应用程序通过订阅来订阅该事件。

-- Ports.elm

port fetchCsrfToken : () -> Cmd msg
port csrfTokenReciever : (String -> msg) -> Sub msg
-- Main.elm

init : Flags -> Url -> Key -> ( Model, Cmd Msg )
init flags url key =
-- ...
(model, Ports.fetchCsrfToken ())


subscriptions : Model -> Sub Msg
subscriptions model =
Ports.csrfTokenReciever GotCsrfToken
// index.js

app.ports.fetchCsrfToken.subscribe(function (str) {
const value = getCookie('csrftoken')
if (value === null) {
app.ports.csrfTokenReciever.send('')
} else {
app.ports.csrfTokenReciever.send(value)
}
})

关于cookies - 如何在Elm中读取cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70218177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com