在使用javascript的天蓝色函数中如何调用发送请求到端点 [英] In azure functions using javascript how to call send request to a endpoint

查看:8
本文介绍了在使用javascript的天蓝色函数中如何调用发送请求到端点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Azure 函数中如何使用 javascript 调用 API.请求是带有标头的 POST.我尝试使用 XMLHttpRequest,但出现了异常,例如未定义 XMLHttpRequest.

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,

推荐答案

您可以使用内置的 http 模块(node.js 的标准模块):

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();
};

如果您将其安装到您的函数应用程序中,您还可以使用任何其他 npm 模块,例如 request.

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

这篇关于在使用javascript的天蓝色函数中如何调用发送请求到端点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆