QSpider QSpider - 6 months ago 22
Ajax Question

Using ajax in Servant

I use Haskell with

servant-0.7.1
fo realisation server.Below is my source code:

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"


The model of
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)


For testin
curl
was used, as shown below.

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


Everything is working. The data added to the database.But when I use
ajax
from backend, as shown below.

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)
}
});


I get an error!

jquery.js:4 POST http://127.0.0.1:3000/rest/user 400 (Bad Request)


The debugger checked object
objectData
. All right (
Object {userFam: "qqq", userIm: "www", userOt: "eee", userEmail: "rrr", userLogin: "ttt"…}
).
I can not understand what was going on.

Answer

it's really a problem with your ajax call as you don't provide a valid JSON object but just objectData.toString() as data: - the common solution is to use 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)
    }
});

another great example what is wrong with untyped languages ;)