簡體   English   中英

nodejs unirest發布請求-如何發布復雜的rest / json主體

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

以下是我用於發布簡單請求的unirest代碼。

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

        });

但是現在需要通過POST調用發送一個復雜的json主體,如下所示:

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

怎么辦呢? 什么是合適的語法來做到這一點?

來自文檔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) {

        });

為此使用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"
            }
        }
    }
};

嘗試在第二個標頭之后添加以下代碼(用於您的對象):

.body(JSON.stringify(objToSending))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM