Search code examples
node.jsapipostmanstormpath

Sending URL encoded string in POST request using node.js


I am having difficulty sending a url encoded string to the Stormpath /oauth/token API endpoint. The string is meant to look like this:

 grant_type=password&username=<username>&password=<password>

Using Postman I was successful in hitting the endpoint and retrieving the data I want by providing a string similar to the one above in the request body by selecting the raw / text option. But when I generate the code snippet it looks like this:

var request = require("request");

var options = { method: 'POST',
  url: 'https://<My DNS label>.apps.stormpath.io/oauth/token',
  headers: 
   { 'postman-token': '<token>',
     'cache-control': 'no-cache',
     'content-type': 'application/x-www-form-urlencoded',
     host: '<My DNS label>.apps.stormpath.io',
     accept: 'application/json' },
  form: false };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});

Where did that string go? I would like some help in understanding the disconnect between knowing I sent a url encoded string to the API endpoint using Postman and not seeing it in the code generated by Postman. Because now I don't know how to reproduce a successful call to the endpoint in my actual app.

To me it seems like I should simply provide a body to the request, but the response comes out to be {"error":"invalid_request","message":"invalid_request"}. I have also tried appending the url encoded string to the url but that returns a 404 error.

I'm just now getting back into using an API and am not very experienced doing so.


Solution

  • The form data needs to be posted as an object, here is an example:

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

    Taken from this documentation:

    https://github.com/request/request#forms

    Hope this helps!