【问题标题】:Get headers from http response从 http 响应中获取标头
【发布时间】:2017-11-06 04:35:42
【问题描述】:

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

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 的标头中返回令牌

authUser =
    Http.send "http://localhost:4000/api/login?email=bob@example&password=1234"

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

【问题讨论】:

    标签: elm


    【解决方案1】:

    我可以谦虚地建议你看看我的 elm-jwt 库,以及那里的 get 函数吗?

    Jwt.get token "/api/data" dataDecoder
        |> Jwt.send DataResult
    

    JWT 令牌通常需要作为 Authorization 标头发送,此函数可帮助您创建可传递给 Http.sendJwt.send 的请求类型

    【讨论】:

    • 感谢您的帮助!我的请求是一个简单的请求没有标头,响应有标头 - 我正在尝试获取 response 标头
    【解决方案2】:

    为了从响应中提取标头,您必须使用 Http.requestexpectStringResponse 函数,其中包括包含标头的完整响应。

    expectStringResponse 函数接受一个 Http.Response a 值,因此我们可以创建一个接受标头名称和响应的函数,然后根据是否找到标头返回 Ok headerValueErr msg

    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" 替换为您的目的。

    【讨论】:

    • 我不断收到:BadPayload“未找到标头授权”{ status = { code = 200, message = "OK" }, headers = Dict.fromList [("cache-control","max -age=0, private, must-revalidate"),("content-type","text/plain; charset=utf-8")], url = "localhost:4000/api/login?email=bob@example&password=1234", body = "success" } 当我使用curl我确实得到了授权标头
    • 看起来字典是区分大小写的。您可以尝试记录字典键列表(使用Dict.keys)以查看您是否使用了正确的大小写。
    • 字典似乎只包含部分标题:[ ("cache-control"),("content-type")]
    • Here is a simple web server and working Elm example 表明 Elm 可以检索响应标头中的 Authorization。您确定您的 Elm 测试应用程序指向与您的 curl 示例相同的网址吗? (image of output)
    • 您可以使用Go 编译和运行(在公共目录中运行elm make Main.elm 后通过go run main.go 运行),但实际上,您可以用任何语言编写一个简单的服务器端点来查看授权标头。它不是特定于 Go 的。我很快就举了一个例子。