What is the way to call "Http.post" in elms

I used the http message in elm as follows, but it does not work, and on the server side I get an empty body. Can someone tell me what is wrong with this code. This is the code of my command module

module SignupForm.Commands exposing (..)

import Http exposing(..)
import Json.Decode as Decode exposing (field)
import SignupForm.Models exposing (..)
import SignupForm.Messages exposing (..)
import Json.Encode as Encode
import Debug exposing (log)




memberDecoder : Decode.Decoder UserDetails
memberDecoder =
    Decode.map4 UserDetails
        (field "fname" Decode.string)
        (field "lname" Decode.string)
        (field "email" Decode.string)
        (field "password" Decode.string)



saveUrl : String
saveUrl =
   "http://localhost:4000/userSignup"


saveRequest : UserDetails -> Http.Request UserDetails
saveRequest d =
    Http.request


        { body = memberEncoded d |> Http.jsonBody
        , expect = Http.expectJson memberDecoder
        , headers = defaultRequestHeaders
        , method = "POST"
        , timeout = Nothing
        , url = saveUrl
        , withCredentials = False
        }



defaultRequestHeaders : List Header
defaultRequestHeaders =
    [ Http.header "Content-Type"  "application/x-www-form-urlencoded"
    ]

fetchAll : UserDetails -> Cmd Msg
fetchAll data =
    saveRequest data
        |> Http.send OnSignUp


memberEncoded : UserDetails -> Encode.Value
memberEncoded data =
    let
        list =
            [ ( "fname", Encode.string data.fname )
            , ( "lname", Encode.string data.lname )
            , ( "email", Encode.string data.email )
            , ( "password", Encode.string data.password )
            ]
    in
        list
            |> Encode.object
+4
source share
1 answer

You publish json but declare that you are submitting formdata.

Try to delete:

defaultRequestHeaders : List Header
defaultRequestHeaders =
    [ Http.header "Content-Type"  "application/x-www-form-urlencoded"
    ]

(Note that expectJson will automatically add Http.header "Content-Type" "application/json"for you

+1
source

Source: https://habr.com/ru/post/1668353/


All Articles