gpt4 book ai didi

elm - 从 http 响应中获取 header

转载 作者:行者123 更新时间:2023-12-04 10:14:49 27 4
gpt4 key购买 nike

我是榆树新手,
我有一个登录 api,它在其 hedears 中返回一个 JWT token

curl  http://localhost:4000/api/login?email=bob@example&password=1234

回复:
HTTP/1.1 200 OK
authorization: Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXyLp0aSI6ImefP2GOWEFYWM47ig2W6nrhw
x-expires: 1499255103
content-type: text/plain; charset=utf-8

success

现在我正在尝试编写一个函数,该函数将发送请求并从 elm 的 header 中返回 token
authUser =
Http.send "http://localhost:4000/api/login?email=bob@example&password=1234"

我如何以简单的方式做到这一点?

最佳答案

为了从响应中提取标题,您必须使用 Http.request随着 expectStringResponse 函数,其中包括完整的响应,包括 header 。
expectStringResponse函数需要一个 Http.Response a值,所以我们可以创建一个函数来接受头名称和响应,然后返回 Ok headerValueErr msg取决于是否找到了 header :

extractHeader : String -> Http.Response String -> Result String String
extractHeader name resp =
Dict.get name resp.headers
|> Result.fromMaybe ("header " ++ name ++ " not found")

这可以被请求构建器使用,如下所示:

getHeader : String -> String -> Http.Request String
getHeader name url =
Http.request
{ method = "GET"
, headers = []
, url = url
, body = Http.emptyBody
, expect = Http.expectStringResponse (extractHeader name)
, timeout = Nothing
, withCredentials = False
}

Here is an example on ellie-app.com 返回值 content-type举个例子。您可以替换 "authorization"为您的目的。

关于elm - 从 http 响应中获取 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44368340/

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