elm / http

Make HTTP requests in Elm
https://package.elm-lang.org/packages/elm/http/latest
BSD 3-Clause "New" or "Revised" License
155 stars 46 forks source link

Runtime exception when empty header name is given #53

Open ymtszw opened 5 years ago

ymtszw commented 5 years ago

Steps to reproduce:

module Main exposing (main)

import Browser
import Html exposing (Html, button, div, text)
import Html.Events exposing (onClick)
import Http

type alias Model =
    {}

init : () -> ( Model, Cmd Msg )
init _ =
    ( {}
    , Http.request
        { method = "GET"
        , headers = [ Http.header "" "something" ]
        , url = "https://www.example.com"
        , body = Http.emptyBody
        , expect = Http.expectWhatever (always NoOp)
        , timeout = Nothing
        , tracker = Nothing
        }
    )

type Msg
    = NoOp

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        NoOp ->
            ( model, Cmd.none )

view : Model -> Html Msg
view model =
    div [] []

main : Program () Model Msg
main =
    Browser.element
        { init = init
        , view = view
        , update = update
        , subscriptions = always Sub.none
        }

Result (runtime exception)

Uncaught SyntaxError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': '' is not a valid HTTP header field name.

On the other hand, empty "value" does not cause exception.

Expected behavior/Proposal

What I actually wanted was, conditionally adding/not adding a Http.header based on a variable like so:

...
, headers =
    [ case fooBar of
        Foo str ->
            Http.header "foo" str
        Bar ->
            Http.header "" ""
    , ...
    ]
...

but as it turned out it ends up in a runtime exception.

The latter could be useful since it can be used paired with if or case inside Lists, like I wanted to do.

As for my intent, for now we can just wrap it in a List for the same effect:


...
, headers =
    case fooBar of
        Foo str ->
            [ Http.header "foo" str ]
        Bar ->
            []
    , ...
    ]
...