1

我将 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"…})。我不明白发生了什么事。

4

1 回答 1

2

您的调用确实存在问题,ajax因为您没有提供有效的 JSON 对象,但objectData.toString()正如data:- 常见的解决方案是使用JSON.stringify

$.ajax({
    type: "POST",
    async: true,
    url: "/rest/user",
    dataType: "json",
    cache : false,
    data: JSON.stringify(objectData),
    success: function(result){
         // ...
    },
    error: function(jqXHR, status, err) {
        console.log(err)
    }
});

另一个很好的例子,无类型语言有什么问题;)

于 2016-05-20T07:59:30.403 回答