Get headers from HTTP response
I'm new to elm, I have a login api that returns a JWT token in their hedras
curl http://localhost:4000/api/login?email=bob@example&password=1234
Answer:
HTTP/1.1 200 OK
authorization: Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXyLp0aSI6ImefP2GOWEFYWM47ig2W6nrhw
x-expires: 1499255103
content-type: text/plain; charset=utf-8
success
now i am trying to write a function that will send a request and return a token from headers in knitting
authUser =
Http.send "http://localhost:4000/api/login?email=bob@example&password=1234"
how can i do it in a simple way?
source to share
To extract a header from a response, you will need to use it in Http.request
conjunction with a function expectStringResponse
that includes the complete response, including headers.
The function expectStringResponse
takes on a value Http.Response a
, so we can create a function that takes the header name and response and then returns Ok headerValue
or Err msg
depending on whether the header was found:
extractHeader : String -> Http.Response String -> Result String String extractHeader name resp = Dict.get name resp.headers |> Result.fromMaybe ("header " ++ name ++ " not found")
This can be used by the query builder as follows:
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's an exampleellie-app.com
that returns content-type
an example value . You can substitute "authorization"
for your own purposes.
source to share
May I humbly suggest that you look at my elm-jwt library and get there ?
Jwt.get token "/api/data" dataDecoder
|> Jwt.send DataResult
JWT points should usually be sent as a header Authorization
and this function helps you create a request type that can be passed to Http.send
orJwt.send
source to share