我已经按照以下方式在elm中使用了http帖子,但它无法正常工作,而在服务器端我得到的是空体。 任何人都可以告诉我这个代码有什么问题。这是我的命令模块的代码
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
答案 0 :(得分:1)
您正在发布json,但声明您正在发送formdata。
尝试删除:
defaultRequestHeaders : List Header
defaultRequestHeaders =
[ Http.header "Content-Type" "application/x-www-form-urlencoded"
]
(请注意,expectJson会自动为您添加Http.header "Content-Type" "application/json"