Http request with options method

I want to fetch a url in the form of “https://domain.com?a=a&b=b”, below code can work without problem:

fetchIndexCommand : Cmd Msg
fetchIndexCommand =
Http.get “https://domain.com?a=a&b=b” indexDecoder
|> RemoteData.sendRequest
|> Cmd.map IndexReceived

I am trying to make it another way, make the parameters seperated, as below:

fetchIndexCommand : Cmd Msg
fetchIndexCommand =
indexRequest “https://domain.com” indexDecoder
|> RemoteData.sendRequest
|> Cmd.map IndexReceived

indexRequest : String -> Decoder a -> Http.Request a
indexRequest url decoder =
Http.request
{ method = “GET”
, headers = []
, url = url
, body = Http.jsonBody indexEncoder
, expect = Http.expectJson decoder
, timeout = Nothing
, withCredentials = False
}

indexEncoder : Encode.Value
indexEncoder =
Encode.object
[ ( “a”, Encode.string “a” )
, ( “b”, Encode.string “b” )
]

This will not work, it will return NetworkError of RemoteData, my browser console will show OPTIONS 405 error, as well as on the server end log: REST Method Not Supported (405): Method options not supported at…

The Http.get is also Http.request, why the behaviour is so different? Did I make any mistake?

Is “https://domain.com?a=a&b=b” the actual url you are fetching? Also what domain is your elm app running on?

This sounds very much like a CORS issue. If the second request is not a “simple request” (see the section on the linked page for details on what that is) then the browser will automatically send an HTTP OPTIONS pre-flight request first to check whether the CORS settings for that site will allow your actual request. From your error message (“Method Not Supported (405): Method options not supported…”) it sounds ike the http server doesn’t support OPTIONS http requests and therefore the CORS pre-flight request fails.

my elm app is on my local machine, fetching from remote. So my server has to accept OPTIONS method.

Thank you. I will try to configure my server

indexRequest is a GET, which does not send a body. You would need to POST (maybe PUT, depending on the use case) in order to send a body. The server will of course need to support these methods and handle parsing the body.

Indeed. So to send a GET request, the parameters have to been added to url as “domain.com?a=a&b=b”, No way to encode seperately?

You can use http://package.elm-lang.org/packages/sporto/qs/1.0.0/QS#serialize to encode the query string for a url. If you have a lot of query parameters or a complex use case this may be helpful.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.