POST Http.request in Elm 0.18

2,056 views
Skip to first unread message

bey...@gmail.com

unread,
Jan 18, 2017, 9:22:23 AM1/18/17
to Elm Discuss
I'm trying to use elm-lang/http without success so far. I want to address an API with a POST request via JSON. All my efforts so far result in having the wrong headers.

There are two things I've tried in the following: in both cases the server tells me that it wasn't a POST request but OPTIONS.

I've tried using "Http.post":

jsonify : String -> Http.Body
jsonify str
=
   
Http.jsonBody <| Encode.object [("sentiment", Encode.string str)]


decodeJson
: Decode.Decoder String
decodeJson
=
   
Decode.map2 (\classification status -> classification)
       
(Decode.field "classification" Decode.string)
       
(Decode.field "status" Decode.int)


fetchSentiment
: String -> Cmd Msg
fetchSentiment sentiment
=
   
Http.send Fetch (Http.post (jsonify sentiment) decodeJson)

and a custom request:

fetchSentiment : String -> Cmd Msg
fetchSentiment sentiment =
    Http.send Fetch (postSentiment sentiment decodeJson)

postSentiment : String -> Decode.Decoder String -> Http.Request String
postSentiment sentiment decoder =
    Http.request
        { method = "POST"
        , headers = [(Http.header "Content-Type" "application/json")]
        , url = "http://127.0.0.1:5000/sentiment"
        , body = (jsonify sentiment)
        , expect = Http.expectJson decoder
        , timeout = Nothing
        , withCredentials = False
        }

Is my problem related to the code above, and if so, how can I fix it?

Duane Johnson

unread,
Jan 18, 2017, 9:35:49 AM1/18/17
to elm-d...@googlegroups.com
It sounds like you might be trying to do a "cross-domain" post, i.e. are you running your elm app on one port, and attempting to POST to another port? If so, this is considered "cross-domain". (Of course, if you have an IP address or domain that's different, that's "cross-domain" as well).

If this is the case, then you need to enable CORS requests on the receiving domain. CORS is a way of negotiating access on a server at another "domain" (or port) so that the server can be responsible for accepting or denying AJAX requests from around the internet. One of the steps that occurs during that negotiation is an OPTIONS header request.

Does that help?

Duane

--
You received this message because you are subscribed to the Google Groups "Elm Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elm-discuss+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Matthieu Pizenberg

unread,
Jan 18, 2017, 9:36:11 AM1/18/17
to Elm Discuss
Hi, in case it may be of help, I just did a small test elm project using web api which is available at this repo.
Basically it was to test a way to use api (and authentified api using JWT) that I adapted from a 0.17 tutorial available on the Auth0 website.
Reply all
Reply to author
Forward
0 new messages