Search code examples
javascriptnode.jsunirest

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


Following is the unirest code I am using to post simple requests.

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

        });

But now its required to send a complex json body with the POST call as shown below:

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

How could this be done? What's the appropriate syntax to do this?


Solution

  • Use Request.send method for that.Determines whether data mime-type is form or 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);
    });