简体   繁体   中英

Can someone help me convert this Curl request into node.js

curl 'https://api.twilio.com/2010-04-01/Accounts/AC7f9cc91207db898bb0ddee8e09d707b5/Calls.json' 

X POST \
data-urlencode 'To=+971566820680' \
data-urlencode 'From=+971556309806' \
data-urlencode 'Url=https://api.twilio.com/2010-04-01/Accounts/AC7f9cc91207db898bb0ddee8e09d707b5/Calls.json' \

data-urlencode 'ApplicationSid=APae94ada54ea05d0dabde55dc7a346178' \
data-urlencode 'Method=POST' \
-u AC7f9cc91207db898bb0ddee8e09d707b5:9b96d9f573a7bbcadce5fa88eced3b66

Above is the code I want to convert to NodeJS

Ideally, I want to have an Azure function (written in NodeJS)

If you check out this link - it allows you to convert any curl request into code for several languages. As a result, I was able to come up with this - I made a few changes. Note: you'll need to install request as an npm module:

const request = require('request');

const options = {
    url: 'https://api.twilio.com/2010-04-01/Accounts/AC7f9cc91207db898bb0ddee8e09d707b5/Calls.json',
    method: 'POST',
    auth: {
        'user': 'AC7f9cc91207db898bb0ddee8e09d707b5',
        'pass': '9b96d9f573a7bbcadce5fa88eced3b66'
    }
};

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

request(options, callback);

To convert this code into something that an Azure Function can use, you'll need to set up the context objection that is used for the callback. This is for an Azure 2.0 Function. First, you need to import the npm module needed (and install it in the Kudu area of the Azure Function app). The function stub they give you will give you the module.exports function stub. What I have done below is filled in the code from your curl request and applied it to the Azure function. At the bottom, you'll see context.res . context.res represents the response that calling this Azure function via HTTP will yield. I have filled in the body with the response from the API request that you have asked for.

const rp = require('request-promise');
module.exports = async function (context, req) {

  const options = {
    url: 'https://api.twilio.com/2010-04-01/Accounts/AC7f9cc91207db898bb0ddee8e09d707b5/Calls.json',
    method: 'POST',
    auth: {
      'user': 'AC7f9cc91207db898bb0ddee8e09d707b5',
      'pass': '9b96d9f573a7bbcadce5fa88eced3b66'
    }
  };

  const response = await rp(options);

  context.res = {
    status: 200,
    body: response
  };
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM