Search code examples
javascriptnode.jshttppostxmlhttprequest

Make a url-form-eoncoded HTTP POST request in Node where the request body has non unique keys


I want to make a HTTP POST request with the Node requests library. The request body has multiple non-unique keys. The problem is that I cannot represent the POST body as a Javascript Object since the keys would get overwritten. The request is url-form-encoded. Is there a way to represent the data in the requests library in a way that I don't have to rely on using a Javascript object to represent my request body params?

Sample request body:

{
 dateFrom:2015-10-07,
 dateTo:2015-10-17,
 columns[]:exc_flags,
 columns[]:exc_currency,
 timeZone:55,
 country[]:25,
 country[]:32,
 country[]:6,
 importance[]:1,
 importance[]:2,
 importance[]:3,
 category[]:_employment,
 category[]:_economicActivity,
}

Here columns[], country[], importance[] and category[] keys are repeated.

The standard syntax for making the url-form-encoded request using the requests library would be:

request.post('http://service.com/upload').form({key:'value'})

This approach would not work if there are non-unique keys in the payload.


Solution

  • Your "multiple non-unique keys" are array values. Simply use JSON with an array for repeated values:

    {
      "dateFrom": "2015-10-07",
      "dateTo": "2015-10-17",
      "columns": ["exc_flags", "exc_currency"],
      "timeZone": 55,
      "country": [25, 32, 6],
      "importance": [1, 2, 3],
      "category": ["_employment", "_economicActivity"],
    }