【问题标题】:How to make a promise based HTTP post request (NodeJS) from inside an Azure function?如何从 Azure 函数内部发出基于承诺的 HTTP 发布请求 (NodeJS)?
【发布时间】:2019-09-14 08:24:29
【问题描述】:

我有一个场景,事件中心正在接收数据并且触发 Azure 函数来获取数据,Azure 函数应该使用获取的数据作为有效负载发出 POST 请求并从服务器获取响应。我正在使用基于 Promise 的 npm Http 模块“Axios”,因为响应时间可能因负载而异。 (Azure 函数在 NodeJS 中);问题是,没有 Post 请求通过

尝试过异步 - 等待 Post 请求的调用,仍然无法正常工作。

这里是代码

module.exports = async function (context, eventHubMessages) {
    context.log(`JavaScript eventhub trigger function called for message array ${eventHubMessages}`);

    var data = {};

    eventHubMessages.forEach((message, index) => {
        context.log(`Processed message ${message}`);
        data = message;
    });

    const axios = require('axios');
    module.exports=async function(context,req){

      let response=  await axios.post('http:example.com/post',     
        { 
          data 
        } 
        )
        .then((res) => {
        context.log(`statusCode: ${res.statusCode}`)
        context.log(res)
        })
        .catch((error) => {
        context.error(error)
        })

        context.log(`Output content: ${res}`);

        }
};

这里是function.json

{
  "bindings": [
    {
      "type": "eventHubTrigger",
      "name": "eventHubMessages",
      "direction": "in",
      "eventHubName": "name-eventhub",
      "connection": "eventhub-key",
      "cardinality": "many",
      "consumerGroup": "$Default"
    },
    {
      "type": "http",
      "name": "$return",
      "direction": "out"
    }
   ]
}

预期输出:

Processed message [object]
statusCode : 200
Output content: response // print response in here

实际输出:

Processed message [object]

输出中没有显示状态代码或响应。

【问题讨论】:

  • 这里还有一个问题,你的 module.exports 被分配了两次。你只想这样做一次。我知道 lambda,而不是 azure 函数,所以我不确定函数签名到底如何,但你绝对不想要两个 module.exports

标签: node.js http-post axios azure-functions azure-eventhub


【解决方案1】:

如果你await承诺,你不需要链接thencatch

const axios = require('axios');
module.exports=async function(context,req){
  try {
    const response =  await axios.post('http:example.com/post', {data})
    context.log(`statusCode: ${response.statusCode}`);
    context.log(response);
    return response; // or return a custom object using properties from response
  } catch (error) {
    // If the promise rejects, an error will be thrown and caught here
    context.error(error);
  }
};

【讨论】:

  • 这段代码就像魅力一样,我从发布请求中得到响应。但我也收到一个错误[Error] Error: Choose either to return a promise or call 'done'. Do not use both in your script. 并且该函数在等待大约 5 分钟后自行终止。
  • 此错误已通过在 try 块中调用 context.done() 之前的 return response; 解决。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-25
  • 2022-12-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多