Azure Functions:如何从EventGridTrigger调用HttpTrigger函数
解决方案
错误原因
xhr2 是为浏览器环境设计的XMLHttpRequest实现,Azure Functions Node.js运行时基于服务器端Node.js环境,使用该库会出现兼容性问题,导致报错。推荐使用Node.js原生HTTP模块或Azure Functions HTTP输出绑定来实现需求。
方案一:使用Axios发送HTTP请求(手动调用)
1. 配置package.json
确保包含axios依赖,文件内容如下:
{ "name": "eventgrid-trigger-function", "version": "1.0.0", "dependencies": { "axios": "^1.6.0" } }
部署后通过Kudu执行npm install安装依赖。
2. EventGridTrigger函数的function.json
不需要额外输出绑定,保持基础配置即可:
{ "bindings": [ { "type": "eventGridTrigger", "name": "eventGridEvent", "direction": "in" } ], "scriptFile": "./index.js" }
3. 函数代码(index.js)
用Axios发送请求到OutFunction2:
const axios = require('axios'); module.exports = async function (context, eventGridEvent) { context.log('Event Grid trigger function processed event:', eventGridEvent); // OutFunction2的URL,包含函数密钥(从Azure门户获取) const outFunctionUrl = "https://<your-function-app-name>.azurewebsites.net/api/OutFunction2?code=<your-function-key>"; try { await axios.post(outFunctionUrl, eventGridEvent); context.log('Successfully sent data to OutFunction2'); } catch (error) { context.log.error('Error sending data:', error.message); throw error; } };
方案二:使用HTTP输出绑定(Azure官方推荐)
这种方式无需手动处理HTTP请求,由Azure Functions运行时自动发送请求。
1. EventGridTrigger函数的function.json
添加HTTP输出绑定配置:
{ "bindings": [ { "type": "eventGridTrigger", "name": "eventGridEvent", "direction": "in" }, { "type": "http", "name": "outputHttp", "direction": "out", "method": "post", "url": "https://<your-function-app-name>.azurewebsites.net/api/OutFunction2?code=<your-function-key>" } ], "scriptFile": "./index.js" }
method:设置为OutFunction2接受的请求方法(这里是POST)url:替换为你的OutFunction2的完整URL,包含函数密钥
2. 函数代码(index.js)
直接将事件数据赋值给输出绑定:
module.exports = async function (context, eventGridEvent) { context.log('Event Grid trigger function processed event:', eventGridEvent); // 将事件数据设置到输出绑定,Azure会自动发送POST请求 context.bindings.outputHttp = eventGridEvent; };
注意事项
- 确保OutFunction2的URL和函数密钥正确,可通过Azure门户的函数“获取函数URL”功能获取
- 本地测试时,若OutFunction2运行在本地,需使用本地URL(如
http://localhost:7071/api/OutFunction2),并确保函数处于运行状态 - 部署后需确认依赖已正确安装,可通过Kudu的“调试控制台”查看
node_modules目录
内容的提问来源于stack exchange,提问作者Mohammed Idris
相关产品推荐
相关产品推荐

