Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post nested objects in query string - Node.js

My code is attempting to post data to a Coldfusion API from my local Node.js server. I have managed to communicate with the API and authenticate myself via the request headers. However I am having difficulty actually passing my JSON object through as I cannot get the structure right.

The API does not accept the JSON option of the request module, so that is my easiest option out of the window.

The API is expecting the following:

{ 
    'source': { 
        'customer': {
            'customerlogin': 'myusername',
            'customerpassword': 'mypassword',
         }
     }
}

my code works if I hard code the following body parameter (from a sucessful post by somebody else) into my post.

var Jrequest = require('request');

var options = {
  uri: 'http://myAPI/customerSSO.json',
  headers: {'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': something', 'Timestamp': timestamp},
  method: 'POST',
  body: 'source=%7B%0D%0A++%22customer%22%3A+%7B%0D%0A++++%22customerlogin%22%3A+%22myusername%22%2C%0D%0A++++%22customerpassword%22%3A+%22mypassword%22%2C%0D%0A%09%22success%22%3A+%22%22%0D%0A++%7D%0D%0A%7D' // Working
};


Jrequest(options, function (error, response, body){
    res.send(body);
});

If I send the JSON through in other ways, for example json.stringify(), it is rejected on the grounds that 'source is required but not defined'.

So I suppose my question is, in node.js how do I turn JSON into something that looks like this

'source=%7B%0D%0A++%22customer%22%3A+%7B%0D%0A++++%22customerlogin%22%3A+%22myusername%22%2C%0D%0A++++%22customerpassword%22%3A+%22mypassword%22%2C%0D%0A%09%22success%22%3A+%22%22%0D%0A++%7D%0D%0A%7D'

or have I overlooked another option?

Thanks for any help and apologies if I have used incorrect terminology.

like image 266
Longshot Avatar asked Oct 15 '13 10:10

Longshot


1 Answers

I think this should work:

var querystring = require('querystring');
...
request({
  ...
  headers : { 'Content-Type': 'application/x-www-form-urlencoded', ... },
  body    : 'source=' + querystring.escape(JSON.stringify({
    'customer': {
      'customerlogin': 'myusername',
      'customerpassword': 'mypassword',
    }
  })),
  ...
}, ...)

Your example also contains newlines and carriage returns and such, but I'm assuming those are optional.

like image 76
robertklep Avatar answered Nov 02 '22 23:11

robertklep