如何在Elm 0.17中对具体类型进行http请求和解码响应?

时间:2016-07-09 14:14:02

标签: json http elm

我想创建一个向服务器发出请求并返回解码值的函数。我的请求中有自定义标头,因此我必须使用Http.send功能。

到目前为止,我能够创建任务

getCurrentUser userId authToken err ok =
  let
    request =
      Http.send defaultSettings
        { verb = "GET"
        , headers = [("X-Auth", authToken)]
        , url = "http://os.apiary.com"
        , body = empty
        }

  in
    Task.perform err ok request

type alias User = { name : String, age : Maybe Int }
userDecoder = object2 User ("name" := string) (maybe ("age" := int))

但我不知道在哪里放置解码逻辑。

1 个答案:

答案 0 :(得分:3)

我认为您正在寻找fromJson

getCurrentUser userId authToken err ok =
  let
    request =
      Http.send defaultSettings
        { verb = "GET"
        , headers = [("X-Auth", authToken)]
        , url = "http://os.apiary.com"
        , body = empty
        }

  in
    Http.fromJson userDecoder request
      |> Task.perform err ok