nodejs Unirest Post请求 - 如何发布复杂的休息 / JSON主体



以下是我用来发布简单请求的Unirest代码。

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

,但现在需要发送一个复杂的JSON主体,并带有邮政通话,如下所示:

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

这怎么办?这样做的适当语法是什么?

使用 request.send for thit.ditermines是data mime-type是形式还是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);
});

来自doc http://unirest.io/nodejs.html#request:

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

因此您可以做:

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) {
        });
let objToSending = {
  "Key1": "Val1",
  "SectionArray1": [
    {
      "Section1.1": {
        "Key2": "Val2",
        "Key3": "Val3"
      }
    }
  ],
  "SectionPart2": {
        "Section2.1": {
            "Section2.2": {
                "Key4": "Val4"
            }
        }
    }
};

尝试添加第二个标头此代码(使用您的对象(:

.body(JSON.stringify(objToSending))

最新更新