Jason O.
Jason O.

Reputation: 3300

Specifying Http headers in Elm

My Elm program works fine with the code (excerpt) below using http.get, but I had to changed it to a custom request to specify JWT in the header, and I get the following error due to type mismatch.

I think I need to change the type of request to Http.Request (List QFields) but not sure how to. Apparently, I can't make it like { verb = "Get" ...} decoder because { verb ... } is not a function.

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
            }  

Upvotes: 9

Views: 2764

Answers (1)

dontexist
dontexist

Reputation: 5652

If I understand correctly, you need to use Http.request, instead of Http.get, and supply it a valid record, like this:

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
        }  

Upvotes: 13

Related Questions