如何在 Elm HTTP 请求中设置自定义内容类型

How to set a custom content type in an Elm HTTP request

我正在探索 Elm 在具有遵循 JSON:API 规范的 REST 后端的 single-page 应用程序中的使用。因此,所有资源的内容类型都是 application/vnd.api+json 而不是通常的 application/json。在 Elm SPA 中配置此内容类型的推荐方法是什么?

据我了解,当我使用 Http.expectJson 作为预期的响应类型时,elm/http 会自动将请求 header 内容类型设置为 application/json。我该如何改变它?我是否需要编写自己的包装 Http.request 的请求函数?有没有更简单、侵入性更小的方法?

Content-Type header 是根据 body 设置的,而不是预期的响应(例如,您可以发送 JSON 并期望字节响应,反之亦然).当您使用 jsonBody 时,header 被设置为 application/json,但如果您需要使用其他内容类型,您可以轻松地使用 stringBody

import Json.Encode as Encode

apiJsonBody : Encode.Value -> Body
apiJsonBody value =
    stringBody "application/vnd.api+json" (Encode.encode 0 value)

postBook : Book -> Cmd Msg
postBook book =
  Http.post
    { url = "https://example.com/books"
    , body = apiJsonBody (encodeBook book)
    , expect = Http.expectJson GotBooks (list string)
    }

根据您的描述,听起来您正在尝试设置发送到服务器的 HTTP 请求的 Content-Type header。 Http.expectJson 函数不修改请求 header.

如果您想更改请求 header,您可以使用 Http.stringBody 手动设置发送到服务器的内容类型。这是此类辅助函数的一个简单示例。

postApiJson : String -> (Result Http.Error a -> msg) -> Decoder a -> Json.Encode.Value -> Cmd msg
postApiJson url msg decoder body =
    Http.post
        { url = url
        , expect = Http.expectJson msg decoder
        , body = Http.stringBody "application/vnd.api+json" (Json.Encode.encode 0 body)
        }