以下是我用来发布简单请求的最简单的代码。
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"
}
}
}
}
怎么可以这样做?这样做的恰当语法是什么?
答案 0 :(得分:2)
:
.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) {
});
答案 1 :(得分:2)
使用 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);
});
答案 2 :(得分:1)
let objToSending = {
"Key1": "Val1",
"SectionArray1": [
{
"Section1.1": {
"Key2": "Val2",
"Key3": "Val3"
}
}
],
"SectionPart2": {
"Section2.1": {
"Section2.2": {
"Key4": "Val4"
}
}
}
};
尝试在第二个标题后添加此代码(使用您的对象):
.body(JSON.stringify(objToSending))