【问题标题】:nodejs unirest post request - how to post complex rest / json bodynodejs unirest post request - 如何发布复杂的rest / json body
【发布时间】:2017-05-04 11:30:17
【问题描述】:

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

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"
            }
        }
    }
}

如何做到这一点?执行此操作的适当语法是什么?

【问题讨论】:

    标签: javascript node.js unirest


    【解决方案1】:

    为此使用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】:

      来自文档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) {
      
              });
      

      【讨论】:

        【解决方案3】:
        let objToSending = {
          "Key1": "Val1",
          "SectionArray1": [
            {
              "Section1.1": {
                "Key2": "Val2",
                "Key3": "Val3"
              }
            }
          ],
          "SectionPart2": {
                "Section2.1": {
                    "Section2.2": {
                        "Key4": "Val4"
                    }
                }
            }
        };
        

        尝试在第二个标题之后添加此代码(使用您的对象):

        .body(JSON.stringify(objToSending))
        

        【讨论】:

        • 我想我永远也无法理解那种将 JSON 数据字符串化的怪异方式。每个人都一直在将他们的 JSON 字符串化,然后再重新解析它,此时我不敢问为什么。
        • 在这种情况下,我们将确保 JSON 数据具有正确的结构
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-23
        • 1970-01-01
        相关资源
        最近更新 更多