Tareq Salah
Tareq Salah

Reputation: 3718

Send Array in post request using node.js using application/x-www-form-urlencoded

I tried to send post request to API and the post parameters should be array, this is how to send it in cURL

curl http://localhost:3000/check_amounts
  -d amounts[]=15 \
  -d amounts[]=30

I tried to do that in Node.js using request module

request.post('http://localhost:3000/check_amounts', {
        form: { 
                'amounts[]': 15 ,
                'amounts[]': 30
              }
    }, function(error, response, body) {
        console.log(body)
        res.json(body);
    });

but the second amount override the first one and the API gets the result as following: amounts = [30]

Then I tried to send it in different way

 request.post('http://localhost:3000/check_amounts', {
            form: { 
                    'amounts[]': [ 15 , 30]
                  }
        }, function(error, response, body) {
            console.log(body)
            res.json(body);
        });

but the result was not as an expected amounts = [{"0":15},{"1":30}]

Note : the header should contains 'Content-Type': 'application/x-www-form-urlencoded' not 'application/json'

Does any one have solution to this problem?

Upvotes: 2

Views: 8816

Answers (1)

Mike
Mike

Reputation: 349

It's quite easy if you read the manual of request. All you should do is replace the form by querystring rather than object, in your case this should be:

amounts=15&amounts=30

the only thing I'm not sure is the above expression works in your web server. As I know it works well in java struts. So if not you may try amounts[]=15&amounts[]=30 instead. Hope it help.

Upvotes: 5

Related Questions