2017-06-05 235 views
1

我是新來的榆樹, 我有一個登錄API,它在其hedears返回JWT令牌GET請求頭

curl http://localhost:4000/api/[email protected]&password=1234 

響應:

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

success 

現在我試着寫一個功能,將發送請求並從榆木頭返回令牌

authUser = 
    Http.send "http://localhost:4000/api/[email protected]&password=1234" 

我該怎麼辦這以一種簡單的方式?

回答

3

我可以虛心地建議你看看我的elm-jwt庫和那裏的get函數嗎?

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

JWT令牌通常需要送到作爲Authorization頭和該功能可幫助您創建一個可以傳遞給Http.sendJwt.send

+0

感謝您的幫助!我的請求是一個簡單的請求**沒有**頭,響應有頭 - 我試圖得到**響應**頭 – dina

4

爲了從響應提取頭的請求類型,將不得不使用Http.request以及expectStringResponse函數,其中包括包含標題的完整響應。

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返回的值以爲例。您可以用"authorization"替代您的用途。

+0

我繼續得到: BadPayload「頭授權未找到」{狀態= {code = 200,message =「OK」},headers = Dict.fromList [(「cache-control」,「max-age = 0,private,must-revalidate」),(「content-type」,「text/plain; charset = utf-8「)],url =」http:// localhost:4000/api/login?email = bob @ example&password = 1234「,body =」success「} 我使用'curl'授權標題 – dina

+0

它看起來像字典區分大小寫。您可以嘗試記錄字典鍵列表(使用'Dict.keys')來查看您是否使用了正確的外殼。 –

+0

詞典似乎只包含部分標題:[(「cache-control」),(「content-type」)] – dina