如何在HTTP请求中获取响应头?

4
我有以下代码,其中我进行了一个带有JWToken授权头的post请求。 我希望从响应头中提取JWToken,并使用端口将其保存在本地存储中。 如何获取Response? 我看到Response类型中的Metadata具有Headers。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
        }
1个回答

3
你可以使用 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
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接