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?
To view the request or response HTTP headers in Google Chrome, take the following steps : In Chrome, visit a URL, right click , select Inspect to open the developer tools. Select Network tab. Reload the page, select any HTTP request on the left panel, and the HTTP headers will be displayed on the right panel.
A response header is an HTTP header that can be used in an HTTP response and that doesn't relate to the content of the message. Response headers, like Age , Location or Server are used to give a more detailed context of the response.
If you want to retrieve all headers of response then use headers() or getHeaders() who return Headers object.
We then fetch this request using fetch() , extract a blob from the response using Response. blob , create an object URL out of it using URL. createObjectURL , and display this in an <img> . Note that at the top of the fetch() block, we log the response headers to the console.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With