繁体   English   中英

如何将数据从 node.js 发送到 azure 事件网格中的主题端点

[英]how to send data to topic endpoint in a azure event grid from node js

如何从 NodeJS 将数据发送到 azure 事件网格中的主题端点

我在 azure 事件网格中创建了一个主题。 我需要从 NodeJS Api 调用向它发送短信数据。 我怎样才能从 NodeJS 发送它。

要从 Node.js 应用程序向 Azure 事件网格主题发送数据,可以使用 Azure 事件网格 Node.js SDK。 以下是如何操作的示例:

首先,安装 Azure 事件网格 Node.js SDK:

npm install @azure/eventgrid

从 Azure 事件网格 Node.js SDK 导入 EventGridPublisherClient 类:

const { EventGridPublisherClient } = require('@azure/eventgrid');

然后,创建 EventGridPublisherClient 类的实例,将事件网格主题的端点和访问密钥作为参数传入:

const eventGridClient = new EventGridPublisherClient(
  '<EVENT_GRID_TOPIC_ENDPOINT>',
  '<EVENT_GRID_TOPIC_ACCESS_KEY>'
);

现在,您可以通过调用 eventGridClient 实例上的 sendEvent 方法并将事件数据作为参数传入,将数据发送到您的事件网格主题。 例如,要发送 SMS 消息事件,您可以这样做:

const eventData = {
  id: '1',
  eventType: 'SmsSent',
  data: {
    phoneNumber: '+1234567890',
    message: 'Hello, world!'
  },
  subject: 'sms/sent',
  eventTime: new Date()
};

eventGridClient.sendEvent(eventData)
  .then(() => {
    console.log('Event published successfully.');
  })
  .catch((err) => {
    console.error('Error publishing event:', err);
  });
  • 您可以使用 `` Npm package 创建事件网格客户端,然后将客户端发布到事件网格。

  • 但首先您需要端点和访问密钥。 对于端点,您可以在overview部分获得在此处输入图像描述

您可以在accesskey选项卡中获取访问密钥

在此处输入图像描述

您可以使用以下代码使用事件网格客户端发布事件并发布 function

代码:

var  uuid = require('uuid').v4;
var  msRestAzure = require('ms-rest-azure');
var  eventGrid = require("azure-eventgrid");
var  url = require('url');
  

function  EventGridSample() {
// TODO: Enter value for topicKey

let  topicKey = '<your AccessKey>';

// TODO: Enter value for topic-endpoint

let  topicEndPoint = '<Your Endpoint >';

  


let  topicCreds = new  msRestAzure.TopicCredentials(topicKey);
let  eventGridClient = new  eventGrid(topicCreds);

let  topicUrl = url.parse(topicEndPoint, true);

let  topicHostName = topicUrl.host;

let  currentDate = new  Date();

// the event which will be sent
let  events = [
{
id:  uuid(),
subject:  'Door1',
dataVersion:  '2.0',
eventType:  'Contoso.Items.ItemReceivedEvent',
data: {
itemSku :  'ContosoItemSku'
},
eventTime:  currentDate
}
];

eventGridClient.publishEvents(topicHostName, events).then((result) => {
    return  Promise.resolve(console.log('Published events successfully.'));
}).catch((err) => {
    console.log('An error ocurred ' + err);
});
}
EventGridSample();

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM