Yaseen Ahmad Yaseen Ahmad - 2 years ago 263
Node.js Question

how to send curl Authorization -u of curl in node js?

I don't know how to send the curl -u in node js i try the following code but no luck.

url: "https://preview.twilio.com/HostedNumbers/HostedNumberOrders",
method: "POST",
json: true,
headers: {
"content-type": "application/json",
"Authorization": accountSid + authToken
json: {
"PhoneNumber": payload.phonenumber, "SmsCapability": true, "IsoCountry": payload.isocountry,
"AddressSid": address.sid, "Email": payload.email,
"FriendlyName": payload.friendlyname, "StatusCallbackUrl": "http://example.com/callback",
"StatusCallbackMethod": "POST",
}, function (error, response, body) {
res.json({ 'error': error, 'data': response, 'body': body });
return true;

this is the curl which i want to call.

curl -XPOST https://preview.twilio.com/HostedNumbers/HostedNumberOrders \
-d "PhoneNumber=+18312011484" \
-d "SmsCapability=true" \
-d "IsoCountry=US" \
-d "Email=hostedsms@twilio.com" \
-d "FriendlyName=HostedNumberOrder1" \
-d "StatusCallbackUrl=http://example.com/callback" \
-d "StatusCallbackMethod=POST" \

yes i know there is some answers but that not solved my problem.

Answer Source

Twilio api

Twilio supports HTTP Basic and Digest Authentication. This allows you to password protect your TwiML URLs on your web server so that only you and Twilio can access them.

See: docs

Request: http authentication

Digest authentication is supported, but it only works with sendImmediately set to false; otherwise request will send basic authentication on the initial request, which will probably cause the request to fail.

See: docs

var options = {
  url: 'https://preview.twilio.com/HostedNumbers/HostedNumberOrders',
  auth: {
    user: username,
    password: password,
    sendImmediately: true

request(options, function (err, res, body) {
  if (err) {
  console.dir('headers', res.headers)
  console.dir('status code', res.statusCode)

Note that you can also specify basic authentication using the URL itself, as detailed in RFC 1738. Simply pass the user:password before the host with an @ sign:

var username = 'username',
    password = 'password',
    url = 'http://' + username + ':' + password + '@some.server.com';

request({url: url}, function (error, response, body) {
   // Do more stuff with 'body' here 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download