2016-02-14 50 views
0

我試圖從POST請求中的有效內容中創建JSON對象,但似乎無法使其工作。我使用BaasBox和我創建了一個JavaScript的插件,看起來像這樣:來自BaasBox中的POST請求的JSON對象

http().post(function(req){ 
    Box.log(req.method + " received: " + req); 
    var jsonObject = JSON(req.body); 
    Box.log("JSON parsed successfully"); 

    var message = new Object(); 
    message.message = jsonObject["message"]; 
    message.firstname = jsonObject["firstname"]; 
    message.lastname = jsonObject["lastname"]; 

    var doc = Box.Documents.save("Messages",message); 
    Box.log("Messages created: " + doc.id); 
    return {status: 200, content: message}; 
}); 

這是一個簡單的腳本,試圖創建請求主體JSON對象。從iOS客戶端應用程序的JSON看起來是這樣的:

let json = "{ \"firstname\" : \"John\" , \"lastname\" : \"Jones\" , \"message\" : \"Hello there\" }" 

現在,這裏的一個有趣的現象:如果我只存儲要求身體像這個代替,那麼JSON成功地存儲爲文檔。

http().post(function(req){ 
    Box.log(req.method + " received: " + req); 

    var doc = Box.Documents.save("Messages",req.body); 
    Box.log("Messages created: " + doc.id); 
    return {status: 200, content: req.body}; 
}); 

如何從請求主體創建JSON對象?

+0

嘗試改變'VAR的JSONObject = JSON(req.body);''到VAR的JSONObject = JSON.parse(req.body);' – th1rdey3

+0

哎呦,從我身邊敲錯!但那不起作用:( –

+1

你有沒有嘗試過'var doc = Box.Documents.save(「Messages」,JSON.stringify(message));'? – th1rdey3

回答

0

原來,req.body不是一個實際的字符串。下面是工作更新後的代碼:

http().post(function(req){ 
    Box.log(req.method + " received: " + req); 
    var jsonString = JSON.stringify(req.body); 
    var jsonObject = JSON.parse(jsonString); 
    Box.log("JSON parsed successfully"); 

    var message = new Object(); 
    message.message = jsonObject["message"]; 
    message.firstname = jsonObject["firstname"]; 
    message.lastname = jsonObject["lastname"]; 

    var doc = Box.Documents.save("Messages",message); 
    Box.log("Messages created: " + doc.id); 
    return {status: 200, content: message}; 
});