我有以下代码,我在其中发出发布请求,并且在我的服务器中设置了带有 JWToken 的授权 header 。我希望从响应 header 中提取 JWToken 并使用端口将其保存在本地存储中。 如何获得响应?我看到在 Response 类型中有 Headers 的元数据。引用 - 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
}
最佳答案
您可以使用 Http.expectStringResponse
获取 Response
和 header 或 Http.expectBytesResponse
而不是 Http.expectWhatever
。
这是一个定义便利函数 expectJWT
的示例,它将检索并返回 Authorization
header ,或者如果它不存在则返回 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
}
关于http - 如何根据 HTTP 请求获取响应 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56403905/