8

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,

3
  • Please post your essential code. Thanks! Commented Jun 12, 2018 at 20:15
  • I need to call an endpoint which accepts POST method with cookie in header which I'll pass. But I am facing problem in achieving this. Commented Jun 12, 2018 at 20:27
  • What is your Azure Functions language? Also like @David suggested can you post your current code? Commented Jun 12, 2018 at 20:28

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

7 Comments

That could mean it works :) Have a look at logs and response to understand the reason.
can i replace host,port and path with url. As I saw in some examples.
You can make any valid use of http or https modules that you find in any Node.js example online, it's no different here
in log i'm getting 2018-06-12T21:08:14.299 [Error] Exception while executing function: Functions.HttpTriggerJS1. mscorlib: One or more errors occurred. Error: Cannot find module 'request'
Hmm... My code has no reference to request module.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.