Reputation: 4289
I am new to elm, I have a login api which returns a JWT token in its hedears
curl http://localhost:4000/api/login?email=bob@example&password=1234
response:
HTTP/1.1 200 OK
authorization: Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXyLp0aSI6ImefP2GOWEFYWM47ig2W6nrhw
x-expires: 1499255103
content-type: text/plain; charset=utf-8
success
now Im trying to write a function that will send request and return the token from the headers in elm
authUser =
Http.send "http://localhost:4000/api/login?email=bob@example&password=1234"
how do I do this in a simple way?
Upvotes: 8
Views: 5097
Reputation: 36385
In order to extract a header from a response, you will have to use Http.request
along with the expectStringResponse
function, which includes the full response including headers.
The expectStringResponse
function takes a Http.Response a
value, so we can create a function that accepts a header name and a response, 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 could be used by a request builder like so:
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
which returns the value of content-type
as an example. You can substitute "authorization"
for your purposes.
Upvotes: 14
Reputation: 21047
May I humbly suggest you look at my elm-jwt library, and the get function there?
Jwt.get token "/api/data" dataDecoder
|> Jwt.send DataResult
JWT tokens normally need to be sent as a Authorization
header and this function helps you create a Request type that can be passed to Http.send
or Jwt.send
Upvotes: 3