如何从Azure函数内部进行基于承诺的HTTP发布请求(NodeJS)?

时间:2019-04-25 00:23:57

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

我有一个场景,其中事件中心正在接收数据,并且触发了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]

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

1 个答案:

答案 0 :(得分:0)

如果您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);
  }
};