BaasBox中来自POST请求的JSON对象

时间:2016-02-14 12:27:07

标签: javascript json baasbox

我正在尝试在POST请求中从有效负载创建JSON对象,但似乎无法使其正常工作。我正在使用BaasBox,我创建了一个如下所示的JavaScript插件:

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就会成功存储为Document。

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对象?

1 个答案:

答案 0 :(得分: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};
});