1

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.

QSpider
  • 537
  • 2
  • 10
  • Have you tried with [servant-js](http://hackage.haskell.org/package/servant-js)? It lets you generate jQuery-based functions for querying your service. Even if you don't want to use it, you might want to compare the JS code generated there with yours. – Alp Mestanogullari May 20 '16 at 07:19
  • IMO your object data does not look right - see here https://stackoverflow.com/questions/4159701/jquery-posting-valid-json-in-request-body – Random Dev May 20 '16 at 07:44
  • in short can you try this with: `dataType: "json"`, `data: JSON.stringify(objectData)` (right now you are using `.toString()` on your `objectData` this is wher ethe `Object` part comes from and this is not valid JSON) – Random Dev May 20 '16 at 07:46
  • I tried `JSON.stringify(objectData)`. Now it works!!! Thank you very much for the idea with `JSON.stringif`. – QSpider May 20 '16 at 07:52
  • I'll add it as an answer I hope you don't mind – Random Dev May 20 '16 at 07:57

1 Answers1

2

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

Random Dev
  • 51,810
  • 9
  • 92
  • 119