简体   繁体   English

来自BaasBox中POST请求的JSON对象

[英]JSON object from POST request in BaasBox

I'm trying to create a JSON object from the payload in a POST request but can't seem to get it working. 我正在尝试从POST请求中的有效负载创建JSON对象,但似乎无法使其正常工作。 I'm using BaasBox and I've created a JavaScript plugin that looks like this: 我正在使用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};
});

It's a simple script that attempts to create a JSON object from the request body. 这是一个简单的脚本,试图从请求主体创建JSON对象。 The JSON from the iOS client application looks like this: 来自iOS客户端应用程序的JSON如下所示:

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

Now here's the interesting part: If I just store the request body like this instead, then the JSON is successfully stored as a Document. 现在,这是有趣的部分:如果我只是这样存储请求正文,则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};
});

How can I create a JSON object from the request body? 如何从请求主体创建JSON对象?

Turns out that the req.body wasn't an actual string. 原来req.body不是实际的字符串。 Here's the updated code that works: 这是有效的更新代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM