'--data-urlencode curl to Node.js request or express module

I am trying to transform this curl command

curl '<url>' -X POST \
  --data-urlencode 'To=<phone>' \
  --data-urlencode 'From=<phone>' \
  --data-urlencode 'Body=<message>' \
  -u '<user>:<pass>'

into this Node.js code

var request = require('request');

var options = {
    url: 'url',
    method: 'POST',
    auth: {
        'user': 'user',
        'pass': 'pass'
    }
};

function callback(error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body);
    }
}

request(options, callback);

I don't get how I can add the --data-urlencode option in the Node.js version of this code.



Solution 1:[1]

From curl documentation :

--data-urlencode

(HTTP) This posts data, similar to the other -d, --data options with the exception that this performs URL-encoding.

So you would use form option to send form URL encoded like this :

var options = {
    url: 'url',
    method: 'POST',
    auth: {
        'user': 'user',
        'pass': 'pass'
    },
    form: {
        To: 'phone',
        From: 'phone',
        Body: 'message'
    },
    headers: {
        'Accept': '*/*'
    }
};

Note that you can use request-debug to show the actual request where you could check that body is :

To=phone&From=phone&Body=message

And to show the actual data sent by curl use as stated here, use --trace-ascii /dev/stdout :

curl '<url>' -X POST --data-urlencode "Body=<message>" -u <user>:<pass>  --trace-ascii /dev/stdout

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community