简体   繁体   English

nodejs unirest发布请求-如何发布复杂的rest / json主体

[英]nodejs unirest post request - how to post complex rest / json body

Following is the unirest code I am using to post simple requests. 以下是我用于发布简单请求的unirest代码。

urClient.post(url)
    .header('Content-Type', 'application/json')
    .header('Authorization', 'Bearer ' + token)
    .end(
        function (response) {

        });

But now its required to send a complex json body with the POST call as shown below: 但是现在需要通过POST调用发送一个复杂的json主体,如下所示:

{
  "Key1": "Val1",
  "SectionArray1": [
    {
      "Section1.1": {
        "Key2": "Val2",
        "Key3": "Val3"
      }
    }
  ],
  "SectionPart2": {
        "Section2.1": {
            "Section2.2": {
                "Key4": "Val4"
            }
        }
    }
}

How could this be done? 怎么办呢? What's the appropriate syntax to do this? 什么是合适的语法来做到这一点?

from the doc http://unirest.io/nodejs.html#request : 来自文档http://unirest.io/nodejs.html#request

.send({
  foo: 'bar',
  hello: 3
})

so you can do: 因此,您可以执行以下操作:

urClient.post(url)
    .header('Content-Type', 'application/json')
    .header('Authorization', 'Bearer ' + token)
    .send(myComplexeObject) // You don't have to serialize your data (JSON.stringify)
    .end(
        function (response) {

        });

Use Request.send method for that.Determines whether data mime-type is form or json. 为此使用Request.send方法确定数据mime-type是form还是json。

var unirest = require('unirest');

unirest.post('http://example.com/helloworld')
.header('Accept', 'application/json')
.send({
  "Key1": "Val1",
  "SectionArray1": [
    {
      "Section1.1": {
        "Key2": "Val2",
        "Key3": "Val3"
      }
    }
  ],
  "SectionPart2": {
        "Section2.1": {
            "Section2.2": {
                "Key4": "Val4"
            }
        }
    }
})
.end(function (response) {
  console.log(response.body);
});
let objToSending = {
  "Key1": "Val1",
  "SectionArray1": [
    {
      "Section1.1": {
        "Key2": "Val2",
        "Key3": "Val3"
      }
    }
  ],
  "SectionPart2": {
        "Section2.1": {
            "Section2.2": {
                "Key4": "Val4"
            }
        }
    }
};

try add after second header this code (used your object): 尝试在第二个标头之后添加以下代码(用于您的对象):

.body(JSON.stringify(objToSending))

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

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