nodejs unirest post request – 如何发布复杂的rest / json主体

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

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

但是现在它需要发送一个复杂的json主体POST调用,如下所示:

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

这怎么可能呢? 什么是适当的语法来做到这一点?

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

从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))