Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In azure functions using javascript how to call send request to a endpoint

In Azure function how to call an API using javascript. The request is POST with the header.I tried to use XMLHttpRequest, but i got exception like this XMLHttpRequest is not defined.

var client = new XMLHttpRequest();
    var authentication = 'Bearer ...'
    var url = "http://example.com";
    var data = '{.........}';

    client.open("POST", url, true);
    client.setRequestHeader('Authorization',authentication); 
    client.setRequestHeader('Content-Type', 'application/json');

    client.send(data);

Any other method is there to achive this,

like image 819
ashok Avatar asked Jun 12 '18 18:06

ashok


People also ask

Can we call API from Azure function?

Depending upon your requirement you can create any of supported trigger to trigger your function app and your function app code will make the HTTP calls. You can refer to Call a Web API From a . NET Client (C#) document for more details.

Can you trigger an Azure function using an HTTP request?

The HTTP trigger lets you invoke a function with an HTTP request. You can use an HTTP trigger to build serverless APIs and respond to webhooks. The default return value for an HTTP-triggered function is: HTTP 204 No Content with an empty body in Functions 2.


1 Answers

You can do it with a built-in http module (standard one for node.js):

var http = require('http');

module.exports= function (context) {
  context.log('JavaScript HTTP trigger function processed a request.');

  var options = {
      host: 'example.com',
      port: '80',
      path: '/test',
      method: 'POST'
  };

  // Set up the request
  var req = http.request(options, (res) => {
    var body = "";

    res.on("data", (chunk) => {
      body += chunk;
    });

    res.on("end", () => {
      context.res = body;
      context.done();
    });
  }).on("error", (error) => {
    context.log('error');
    context.res = {
      status: 500,
      body: error
    };
    context.done();
  });
  req.end();
};

You can also use any other npm module like request if you install it into your Function App.

like image 64
Mikhail Shilkov Avatar answered Nov 01 '22 00:11

Mikhail Shilkov