【问题标题】:How to get Response Headers upon HTTP Request?如何根据 HTTP 请求获取响应标头?
【发布时间】:2025-05-19 04:50:01
【问题描述】:

我有以下代码,我在其中发出发布请求,并在我的服务器中设置了带有 JWToken 的 Authorization 标头。我希望从响应头中提取 JWToken 并使用端口将其保存在本地存储中。 如何获取响应?我看到元数据在响应类型中有标题。参考 - 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 http-headers jwt elm


    【解决方案1】:

    您可以使用Http.expectStringResponseHttp.expectBytesResponse 而不是Http.expectWhatever 来访问Response 和标头。

    这是一个定义便利函数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
            }
    

    【讨论】: