Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

--data-urlencode curl to nodeJS request or express module

Tags:

node.js

curl

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.

like image 533
Amine Avatar asked Feb 28 '17 15:02

Amine


1 Answers

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
like image 122
Bertrand Martel Avatar answered Sep 29 '22 13:09

Bertrand Martel