我将 Haskell 与servant-0.7.1
实现服务器一起使用。以下是我的源代码:
type UserRestAPI
= "rest" :> "users" :> Get '[JSON] [User]
:<|> "rest" :> "user" :> ReqBody '[JSON] User :> Post '[PlainText] Text
serverUserRestAPI :: ServerT UserRestAPI AppM
serverUserRestAPI = usersGet :<|> userPost
userPost :: User -> AppM Text
userPost user = do
newUser <- runDb $ do insert user
liftIO $ putStrLn $ show newUser
return $ append (toPathPiece newUser) "\r\n"
型号User
:
let mongoSettings = (mkPersistSettings (ConT ''MongoContext)) {mpsGeneric = False}
in share [mkPersist mongoSettings, mkMigrate "migrateAll"] [persistLowerCase|
User
fam String
im String
ot String
email String
login String
pswd String
deriving Show
|]
$(deriveJSON defaultOptions ''User)
使用了testin curl
,如下图所示。
curl --verbose --request POST --header "Content-Type: application/json" \
--data '{"userFam": "Fam", "userIm": "Im", "userOt": "Ot", "userEmail": "mail@mail.ru", "userLogin": "test", "userPswd": "test"}' \
http://127.0.0.1:3000/rest/user
一切正常。将数据添加到数据库中。但是当我ajax
从后端使用时,如下图所示。
var formElement = $("#id_form");
var formData = formElement.serializeArray();
var objectData = {};
for(var i = 0; i < formData.length; i++)
objectData[formData[i].name] = formData[i].value;
$.ajax({
type: "POST",
async: true,
url: "/rest/user",
dataType: "text",
cache : false,
contentType : "application/json",
data: objectData,
success: function(result){
consoloe.log(result)
},
error: function(jqXHR, status, err) {
console.log(err)
}
});
我得到一个错误!
jquery.js:4 POST http://127.0.0.1:3000/rest/user 400 (Bad Request)
调试器检查对象objectData
。好的(Object {userFam: "qqq", userIm: "www", userOt: "eee", userEmail: "rrr", userLogin: "ttt"…}
)。我不明白发生了什么事。