onkar-cis
onkar-cis

Reputation: 41

What is the way of making "Http.post" call in elm

I have used the http post in elm in following manner but it is not working and on server side I am getting the empty body. Can anybody 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

Upvotes: 4

Views: 3184

Answers (1)

Simon H
Simon H

Reputation: 21047

You are posting json, but declaring that you are sending formdata.

Try removing:

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

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

Upvotes: 1

Related Questions