在Elm中指定Http头

时间:2017-04-07 07:18:12

标签: http elm

我的Elm程序使用http.get下面的代码(摘录)可以正常工作,但我不得不将其更改为自定义请求以在标头中指定JWT,并且由于类型不匹配而出现以下错误。

我想我需要将request的类型更改为Http.Request (List QFields),但不知道该怎么做。显然,我不能像{ verb = "Get" ...} decoder那样,因为{ verb ... }不是函数。

The 2nd argument to function `send` is causing a mismatch.

264|                Http.send FetchHNTopStories request
                                                ^^^^^^^
Function `send` is expecting the 2nd argument to be:

    Http.Request (List QFields)

But it is:

    Request
<Working code>

request : Http.Request (List QFields)
request = 
    let 
       decoder =
        JD.at [ "data", "qQry" ] <|
            JD.list qDecoder
    in
       Http.get ("http://localhost:3000/graphql?query=" ++ encoded) decoder

type Msg
    = SendMessage
    | FetchHNTopStories (Result Http.Error (List QFields))
     ...

initModel : Taco -> ( Model, Cmd Msg )
initModel taco =
    let
        startModel = { newMessage = ""
                    }

        cmd =  Http.send FetchHNTopStories request  
    in
        ( startModel
           ! [cmd]
        )
<Changed code - Not working>

request : Request
request  =
    let

        decoder =
            JD.at [ "data", "Qry" ] <|
                JD.list qDecoder

        headers= [
            ("Authorization","Bearer eyJhbGciOiJIUzUxM...kv6TGw7H1GX2g")
        ]

    in
          { verb = "GET"
            , headers = headers
            , url = url
            , body = Http.emptyBody
            , expect = Http.expectJson decoder
            }  

1 个答案:

答案 0 :(得分:11)

如果我理解正确,您需要使用Http.request而不是Http.get,并为其提供有效记录,如下所示:

request : Http.Request (List QFields)
request =
    let
        decoder =
            JD.at [ "data", "Qry" ] <|
                JD.list qDecoder

        headers =
            [ ( "Authorization", "Bearer eyJhbGciOiJIUzUxM...kv6TGw7H1GX2g" )
            ]
    in
    Http.request -- This line is missing from your code
        { method = "GET"
        , headers = headers
        , url = url
        , body = Http.emptyBody
        , expect = Http.expectJson decoder
        , timeout = Nothing
        , withCredentials = False
        }