nodejs unirest post 请求 - 如何 post 复杂的 rest / json 主体
nodejs unirest post request - how to post complex rest / json body
以下是我用于 post 简单请求的 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"
}
}
}
}
这是怎么做到的?执行此操作的适当语法是什么?
let objToSending = {
"Key1": "Val1",
"SectionArray1": [
{
"Section1.1": {
"Key2": "Val2",
"Key3": "Val3"
}
}
],
"SectionPart2": {
"Section2.1": {
"Section2.2": {
"Key4": "Val4"
}
}
}
};
尝试在第二个 header 之后添加此代码(使用了您的 object):
.body(JSON.stringify(objToSending))
来自文档 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 方法 that.Determines 无论数据 mime 类型是表单还是 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);
});
以下是我用于 post 简单请求的 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"
}
}
}
}
这是怎么做到的?执行此操作的适当语法是什么?
let objToSending = {
"Key1": "Val1",
"SectionArray1": [
{
"Section1.1": {
"Key2": "Val2",
"Key3": "Val3"
}
}
],
"SectionPart2": {
"Section2.1": {
"Section2.2": {
"Key4": "Val4"
}
}
}
};
尝试在第二个 header 之后添加此代码(使用了您的 object):
.body(JSON.stringify(objToSending))
来自文档 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 方法 that.Determines 无论数据 mime 类型是表单还是 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);
});