我具有以下代码,在其中进行发布请求,并在服务器中使用JWToken设置了Authorization标头。我希望从响应头中提取JWToken并使用port将其保存在本地存储中。 如何掌握回应?我看到在响应类型中具有标头的元数据。 ref-https://package.elm-lang.org/packages/elm/http/latest/Http#Response
type Msg
= EnteredEmail String
| EnteredPassword String
| SubmittedForm
| RegistrationSuccess (Result Http.Error ())
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
EnteredEmail email ->
updateForm (\form -> { form | email = email }) model
EnteredPassword password ->
updateForm (\form -> { form | password = password }) model
RegistrationSuccess _->
-- TODO save JWT in local storage on successful registration
(model, Cmd.none)
SubmittedForm ->
-- TODO validate the form
(model, postCall model)
postCall : Model -> Cmd Msg
postCall model = Http.post {
url = "http://localhost:9000/register",
body = Http.jsonBody (
Json.Encode.object[
("age", Json.Encode.int 30),
("email", Json.Encode.string model.form.email),
("password", Json.Encode.string model.form.password)
]
),
expect = Http.expectWhatever RegistrationSuccess
}
答案 0 :(得分:1)
您可以使用Http.expectStringResponse
或Http.expectBytesResponse
而不是Response
来访问Http.expectWhatever
和标题。
下面是一个示例,该示例定义了便捷函数expectJWT
,该函数将检索并返回Authorization
标头,如果不存在,则返回BadStatus 403
。在postCall
中所做的更改只是将Http.expectWhatever
替换为expectJWT
:
expectJWT : (Result Http.Error String -> msg) -> Http.Expect msg
expectJWT toMsg =
Http.expectStringResponse toMsg <|
\response ->
case response of
Http.BadUrl_ url ->
Err (Http.BadUrl url)
Http.Timeout_ ->
Err Http.Timeout
Http.NetworkError_ ->
Err Http.NetworkError
Http.BadStatus_ metadata body ->
Err (Http.BadStatus metadata.statusCode)
Http.GoodStatus_ metadata body ->
metadata.headers
|> Dict.get "Authorization"
|> Result.fromMaybe (Http.BadStatus 403)
postCall : Model -> Cmd Msg
postCall model = Http.post {
url = "http://localhost:9000/register",
body = Http.jsonBody (
Json.Encode.object[
("age", Json.Encode.int 30),
("email", Json.Encode.string model.form.email),
("password", Json.Encode.string model.form.password)
]
),
expect = expectJWT RegistrationSuccess
}