# @azure/notification-hubs 中文文档

规范地址：https://npmcn.com/package/%40azure/notification-hubs/

版本：2\.1\.0
npm 元数据更新时间：2026-05-05T17:23:52.931Z
中文译文更新时间：2026-11-07T13:26:10.441Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40azure/notification-hubs
原文对照：https://npmcn.com/package/%40azure/notification-hubs/?lang=original
项目主页：https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/notificationhubs/notification-hubs/README.md
源码仓库：https://github.com/Azure/azure-sdk-for-js

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：2.7 MB，936 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=20\.0\.0
- 运行依赖：11 个
- 首次发布：2022-08-05T00:52:54.311Z
- 最新版本发布：2026-05-05T17:23:52.704Z
- 近 30 天下载量：83205（2026-10-08 至 2026-11-06，npm 官方下载统计）
- 已发布版本数：492（近 12 个月 68 个）

## 中文简介

JavaScript 的 Azure 通知枢纽 SDK

## 安装

```sh
npm install @azure/notification-hubs
```

也可以使用：`pnpm add @azure/notification-hubs`、`yarn add @azure/notification-hubs`、`bun add @azure/notification-hubs`

## README

# JavaScript 的 Azure 通知枢纽 SDK

Azure Notication Hubs提供一个缩放的推放引擎,使您能够从任何后端(云或地上)向任何平台(Apple, Amazon Kindle, Firebase, Baidu, Xiaomi, Web, Windows等)发送通知. 通知中心对企业和消费者都行之有效。 以下是几个实例:

-   发送即时新闻通知 数百万与低纬度.
-   将基于位置的优惠券发送给感兴趣的用户区段.
-   向用户或团体发送与事件有关的通知,用于媒体/体育/金融/采集应用程序.
-   将促销内容推向应用,以招商和向客户推销.
-   通知新消息和工作项目等企业活动的用户.
-   发送多要素认证代码 .

密钥链接 :

-   [源代码](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/notificationhubs/notification-hubs/)
-   [软件包( npm)](https://www.npmjs.com/package/@azure/notification-hubs)
-   [产品文档](https://learn.microsoft.com/azure/notification-hubs/)
-   [样本](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/notificationhubs/notification-hubs/samples-dev)

**页:1**: 如果你来自使用 `azure-sb` 软件包,参见 [向@azure/ notification-hubs移动的移民指南](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/notificationhubs/notification-hubs/migrationguide.md)

## 开始

### 目前得到支持的环境

-   [节点.js的LTS版本](https://github.com/nodejs/release#release-schedule)
-   Safari,Chrome,Edge,和Firefox的最新版本.

看我们的 [支助政策](https://github.com/Azure/azure-sdk-for-js/blob/main/SUPPORT.md) 更多细节.

### 安装软件包

```bash
npm install @azure/notification-hubs
```

### 先决条件

-   一个 [Azure 订阅](https://azure.microsoft.com/)
-   一个 [应用程序通知枢纽](https://learn.microsoft.com/azure/notification-hubs/) 资源.

### 创建 Azure 通知枢纽资源

可以使用下列方法创建Azure通知枢纽:

1.  [Azure 门户](https://learn.microsoft.com/azure/notification-hubs/create-notification-hub-portal)
2.  [阿苏尔CLI](https://learn.microsoft.com/azure/notification-hubs/create-notification-hub-azure-cli)
3.  [双](https://learn.microsoft.com/azure/notification-hubs/create-notification-hub-bicep)
4.  [ARM 模板](https://learn.microsoft.com/azure/notification-hubs/create-notification-hub-template)

一旦创建,便可以使用 [Azure 门户网站或 Azure CLI](https://learn.microsoft.com/azure/notification-hubs/configure-notification-hub-portal-pns-settings?tabs=azure-portal)。 。 。 .

### 导入客户端

这个用于JavaScript的SDK提供了两种与Azure通知枢纽进行互动的方法,要么通过基于类的方法,要么采用模块化设计方法. 基于类的方法在所有软件包中一致地创建客户端,然后在客户端上与方法交互.

```ts
import { NotificationHubsClient, createAppleInstallation } from "@azure/notification-hubs";

const client = new NotificationHubsClient("<connection string>", "<hub name>");

const installation = createAppleInstallation({
  installationId: "<installation-id>",
  pushChannel: "<push-channel>",
  tags: ["likes_javascript"],
});

const result = await client.createOrUpdateInstallation(installation);
```

模块化方法允许开发者在每种方法单独被曝光时选择要导入的函数. 这种方法使用带有ES-Modules的子路径出口,通过直接进口暴露出方法. 随着个别出口,这创造了更好的摇树体验和更小的捆绑尺寸,开发商可以利用.

请注意,创建客户端是通过 `"@azure/notification-hubs/api"` 子路径和所有客户端方法通过 `"@azure/notification-hubs/api"` 子路径。 导出的每一函数都取 `client` 作为第一个参数和其余参数保持不变.

以下子路径被曝光:

-   `@azure/notification-hubs/api` - 客户通过 `createClientContext` 和客户方法,例如 `getInstallation` 或者说 `sendNotification`
-   `@azure/notification-hubs/models` - 通知中心模型和工厂方法.

上面的代码片段然后变成如下:

```ts
import { createClientContext, createOrUpdateInstallation } from "@azure/notification-hubs/api";
import { createAppleInstallation } from "@azure/notification-hubs";

const context = createClientContext("<connection string>", "<hub name>");

const installation = createAppleInstallation({
  installationId: "<installation-id>",
  pushChannel: "<push-channel>",
  tags: ["likes_javascript"],
});

const result = await createOrUpdateInstallation(context, installation);
```

### 认证客户端

与 Azure 通知中心的互动始于 `NotificationHubsClient` 用于支持 [共享访问签名连接字符串](https://learn.microsoft.com/azure/notification-hubs/notification-hubs-push-notification-security)。这包括以下许可级别: **听着**, (中文(简体) ), **管理**, (中文(简体) ), **发送**。 。 。 .

倾听允许客户端通过注册和安装API自行注册. 发送允许客户端使用发送API向设备发送通知. 最后,"管理"允许用户进行注册和安装管理,如查询.

一个新的 `NotificationHubsClient` 可以使用连接字符串和通知枢纽名称的构造器创建客户端.

```ts
import { NotificationHubsClient } from "@azure/notification-hubs";

const client = new NotificationHubsClient("<connection string>", "<hub name>");
```

采用模块化方法 `createClientContext` 可以通过 `"@azure/notification-hubs/api"` 子路径.

```ts
import { createClientContext } from "@azure/notification-hubs/api";

const context = createClientContext("<connection string>", "<hub name>");
```

## 关键概念

一旦 `NotificationHubClient` 现已初步确定,可探讨以下概念.

-   通过安装和登记进行设备管理
-   向设备发送通知

### 设备管理

设备管理是通知枢纽的一个核心概念,能够存储本地平台通知服务(PNS)中独特的标识符,如APN或Firebase,以及用于向受众发送推力通知的标记等相关元数据. 使用两个API即安装API(较新的首选机制)和注册.

#### 安装 API

安装是一种较新而本土的JSON设备管理方法,它包含额外的属性,如安装ID和用户ID,可用于发送给受众. 与现有的登记辅助设施相比,这些设施具有以下一些优势:

-   Fully idempotent API因此呼叫在安装上创建,所以一个操作可以重审而不担心重复.
-   支助 `userId` 财务报告和审定财务报表 `installationId` 属性,然后可用于标记表达式,例如 `$InstallationId:{myInstallId}` 财务报告和审定财务报表 `$UserId:{bob@contoso.com}`。 。 。 .
-   模板现在成为安装的一部分,而不是单独的注册,可以作为发送标记的名称参考.
-   部分更新通过 [JSON 补丁标准](https://tools.ietf.org/html/rfc6902),它允许添加标签并更改其他数据,而无需首先查询安装.

安装可以通过 `createOrUpdateInstallation` 方法,例如:

```ts
import { NotificationHubsClient, createAppleInstallation } from "@azure/notification-hubs";

const client = new NotificationHubsClient("<connection string>", "<hub name>");

// Create an installation for APNs
const installation = createAppleInstallation({
  installationId: "0d8ab095-c449-493f-9195-17e4917806c4", // Must be unique
  pushChannel: "00fc13adff785122b4ad28809a3420982341241421348097878e577c991de8f0", // PNS specific handle
  tags: ["likes_hockey", "likes_football"],
});

const response = await client.createOrUpdateInstallation(installation);
```

采用模块化方法,编码如下:

```ts
import { createClientContext, createOrUpdateInstallation } from "@azure/notification-hubs/api";
import { createAppleInstallation } from "@azure/notification-hubs";

const context = createClientContext("<connection string>", "<hub name>");

// Create an installation for APNs
const installation = createAppleInstallation({
  installationId: "0d8ab095-c449-493f-9195-17e4917806c4", // Must be unique
  pushChannel: "00fc13adff785122b4ad28809a3420982341241421348097878e577c991de8f0", // PNS specific handle
  tags: ["likes_hockey", "likes_football"],
});

const response = await createOrUpdateInstallation(context, installation);
```

对安装的更新可以通过 JSON 补丁计划进行,例如添加标签和用户ID `updateInstallation` 方法.

```ts
import { NotificationHubsClient, JsonPatch } from "@azure/notification-hubs";

const client = new NotificationHubsClient("<connection string>", "<hub name>");

const installationId = "<unique installation ID>";
const updates: JsonPatch[] = [
  { op: "add", path: "/tags", value: "likes_baseball" },
  { op: "add", path: "/userId", value: "bob@contoso.com" },
];

const installation = await client.updateInstallation(installationId, updates);
```

采用模块化方法,编码如下:

```ts
import { createClientContext, updateInstallation } from "@azure/notification-hubs/api";
import { JsonPatch } from "@azure/notification-hubs";

const context = createClientContext("<connection string>", "<hub name>");

const installationId = "<unique installation ID>";

const updates: JsonPatch[] = [
  { op: "add", path: "/tags", value: "likes_baseball" },
  { op: "add", path: "/userId", value: "bob@contoso.com" },
];

const installation = await updateInstallation(context, installationId, updates);
```

要获取已有的安装, 请使用 `getInstallation` 方法与您现有的唯一安装标识.

```ts
import { NotificationHubsClient } from "@azure/notification-hubs";

const client = new NotificationHubsClient("<connection string>", "<hub name>");

const installationId = "<unique installation ID>";

const installation = client.getInstallation(installationId);
```

采用模块化方法,编码如下:

```ts
import { createClientContext, getInstallation } from "@azure/notification-hubs/api";

const context = createClientContext("<connection string>", "<hub name>");

const installationId = "<unique installation ID>";

const installation = getInstallation(context, installationId);
```

#### 登记 API

登记与上面的安装一样与PNS有关,并带有PNS中唯一的设备标识符和相关标记. 模板注册是创建预定义的机身模板的一种方式,然后可以在发送时根据属性进行定制以填充消息. 关于模板的更多信息,请参见: [模板文档](https://learn.microsoft.com/azure/notification-hubs/notification-hubs-templates-cross-platform-push-messages)。 。 。 .

安装可以采用两种方式之一,首先从服务器获取注册ID `getInstallationId` 接下来 `createOrUpdateRegistration` 或通过 `createRegistration` 方法.

```ts
import {
  NotificationHubsClient,
  createAppleRegistrationDescription,
} from "@azure/notification-hubs";

const client = new NotificationHubsClient("<connection string>", "<hub name>");

const registration = createAppleRegistrationDescription({
  deviceToken: "00fc13adff785122b4ad28809a3420982341241421348097878e577c991de8f0",
  tags: ["likes_hockey", "likes_football"],
});
const updatedRegistration = await client.createRegistration(registration);
```

采用模块化方法,编码如下:

```ts
import { createClientContext, createRegistration } from "@azure/notification-hubs/api";
import { createAppleRegistrationDescription } from "@azure/notification-hubs";

const context = createClientContext("<connection string>", "<hub name>");

const registration = createAppleRegistrationDescription({
  deviceToken: "00fc13adff785122b4ad28809a3420982341241421348097878e577c991de8f0",
  tags: ["likes_hockey", "likes_football"],
});

const updatedRegistration = await createRegistration(context, registration);
```

可通过 `updateRegistration` 方法,但与安装不同,不支持递增更新。 查询现有登记可使用 `getRegistration` 方法.

```ts
import { NotificationHubsClient } from "@azure/notification-hubs";

const client = new NotificationHubsClient("<connection string>", "<hub name>");

const registrationId = "<unique Registration ID>";

const registration = await client.getRegistration(registrationId);

if (registration.tags) {
  registration.tags.push("likes_sports");
} else {
  registration.tags = ["likes_sports"];
}

const updatedRegistration = await client.updateRegistration(registration);
```

采用模块化方法,编码如下:

```ts
import {
  createClientContext,
  getRegistration,
  updateRegistration,
} from "@azure/notification-hubs/api";

const context = createClientContext("<connection string>", "<hub name>");

const registrationId = "<unique Registration ID>";

const registration = await getRegistration(context, registrationId);

if (registration.tags) {
  registration.tags.push("likes_sports");
} else {
  registration.tags = ["likes_sports"];
}

const updatedRegistration = await updateRegistration(context, registration);
```

与设施不同的是,可以查询登记,以便获得所有登记,将登记与条件相匹配,或者通过标记。 登记可使用 `listRegistrations`, (中文(简体) ), `listRegistrationsByChannel` 财务报告和审定财务报表 `listRegistrationsByTag` 方法。 所有方法都支持通过 `top` 选项,并支持同步调用.

```ts
import { NotificationHubsClient } from "@azure/notification-hubs";

const client = new NotificationHubsClient("<connection string>", "<hub name>");

const registrations = client.listRegistrationsByTag("likes_hockey");

let page = 0;
for await (const pages of registrations.byPage()) {
  console.log(`Page number ${page++}`);
  for (const item of pages) {
    console.log(JSON.stringify(item, null, 2));
  }
}
```

采用模块化方法,编码如下:

```ts
import { createClientContext, listRegistrationsByTag } from "@azure/notification-hubs/api";

const context = createClientContext("<connection string>", "<hub name>");

const registrations = await listRegistrationsByTag(context, "likes_hockey");

let page = 0;
for await (const pages of registrations.byPage()) {
  console.log(`Page number ${page++}`);
  for (const item of pages) {
    console.log(JSON.stringify(item, null, 2));
  }
}
```

### 发送操作

通知中心支持向设备发送通知,要么直接使用唯一提供的PNS标识符,使用标记给观众发送,要么向所有设备发送一般广播. 使用标准SKU及以上, [预定发送](https://learn.microsoft.com/azure/notification-hubs/notification-hubs-send-push-notifications-scheduled) 允许用户最多提前七天安排通知。 所有发送操作都返回可用于通知中心支持案件的跟踪ID和关联ID。 使用标准SKU及以上,也可返回通知ID,该ID可用于通过 `getNotificationOutcomeDetails` 方法.

为调试目的 `enableTestSend` 选项可设定为 `true` 立即从PNS获得关于 `sendNotification` 但是,在生产设想中,不支持方法。 计划发送方法不支持此选项 .

Raw JSON 或 XML 字符串可以发送到发送或预定的发送方法,或者可以使用通知构建器来帮助每个PNS构造消息,如APNs,Firebase,Baidu,ADM和WNS. 这些构建者将构建本地信件格式, 因此无法猜测每个 PNS 可用的字段 .

```ts
import { createAppleNotificationBody, createAppleNotification } from "@azure/notification-hubs";

const apnsBody = createAppleNotificationBody({
  alert: {
    title: "Notification Title",
    subtitle: "Notification Subtitle",
    body: "Notification body goes here",
  },
  sound: "default",
  interruptionLevel: "time-sensitive",
});

// Send the message using the modular approach
const notification = createAppleNotification({
  body: apnsBody,
});
```

#### 广播发送

通知中心可用于向每个平台的所有已登记设备发送通知,通过广播发送 `sendBroadcastNotification` 方法.

```ts
import { NotificationHubsClient, createAppleNotification } from "@azure/notification-hubs";

const client = new NotificationHubsClient("<connection string>", "<hub name>");

const messageBody = `{ "aps" : { "alert" : "Hello" } }`;

const message = createAppleNotification({
  body: messageBody,
  headers: {
    "apns-priority": "10",
    "apns-push-type": "alert",
  },
});

const result = await client.sendBroadcastNotification(message);

console.log(`Tracking ID: ${result.trackingId}`);
console.log(`Correlation ID: ${result.correlationId}`);

// Only available in Standard SKU and above
if (result.notificationId) {
  console.log(`Notification ID: ${result.notificationId}`);
}
```

采用模块化方法,编码如下:

```ts
import { createClientContext, sendBroadcastNotification } from "@azure/notification-hubs/api";
import { createAppleNotification } from "@azure/notification-hubs";

const context = createClientContext("<connection string>", "<hub name>");

const messageBody = `{ "aps" : { "alert" : "Hello" } }`;

const message = createAppleNotification({
  body: messageBody,
  headers: {
    "apns-priority": "10",
    "apns-push-type": "alert",
  },
});

const result = await sendBroadcastNotification(context, message);

console.log(`Tracking ID: ${result.trackingId}`);
console.log(`Correlation ID: ${result.correlationId}`);

// Only available in Standard SKU and above
if (result.notificationId) {
  console.log(`Notification ID: ${result.notificationId}`);
}
```

#### 直接发送

要直接发送设备,用户可以通过调用 APNs 设备令牌等提供唯一标识符的平台发送 `sendNotification` 使用一个方法 `deviceHandle` 参数.

```ts
import { NotificationHubsClient, createAppleNotification } from "@azure/notification-hubs";

const client = new NotificationHubsClient("<connection string>", "<hub name>");

const deviceHandle = "00fc13adff785122b4ad28809a3420982341241421348097878e577c991de8f0";
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;

const message = createAppleNotification({
  body: messageBody,
  headers: {
    "apns-priority": "10",
    "apns-push-type": "alert",
  },
});

const result = await client.sendNotification(message, { deviceHandle });

console.log(`Tracking ID: ${result.trackingId}`);
console.log(`Correlation ID: ${result.correlationId}`);

// Only available in Standard SKU and above
if (result.notificationId) {
  console.log(`Notification ID: ${result.notificationId}`);
}
```

采用模块化方法,编码如下:

```ts
import { createClientContext, sendNotification } from "@azure/notification-hubs/api";
import { createAppleNotification } from "@azure/notification-hubs";

const context = createClientContext("<connection string>", "<hub name>");

const deviceHandle = "00fc13adff785122b4ad28809a3420982341241421348097878e577c991de8f0";
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;

const message = createAppleNotification({
  body: messageBody,
  headers: {
    "apns-priority": "10",
    "apns-push-type": "alert",
  },
});

const result = await sendNotification(context, message, { deviceHandle });

console.log(`Tracking ID: ${result.trackingId}`);
console.log(`Correlation ID: ${result.correlationId}`);

// Only available in Standard SKU and above
if (result.notificationId) {
  console.log(`Notification ID: ${result.notificationId}`);
}
```

#### 观众发送

除了针对单个设备,用户还可以使用标记瞄准多个设备. 这些标记可以作为标记列表提供,然后生成一个标记表达式来匹配已注册的设备,或者通过一个标记表达式,然后可以使用布尔逻辑来瞄准正确的受众. 关于标签和标签表达式的更多信息,参见 [运行和标记表达式](https://learn.microsoft.com/azure/notification-hubs/notification-hubs-tags-segment-push-message)。 。 。 .

如果您想从一系列标签中创建标签表达式, 则有一个标签表达式构建器可用, 并带有 `createTagExpression` 在顶端导入时曝光的方法或 `@azure/notification-hubs/models/tagExpressionBuilder` 从标签中创建“ 或标签表达式” 的模块导入 .

```ts
import { createTagExpression } from "@azure/notification-hubs";

const tags = ["likes_football", "likes_hockey"];
const tagExpression = createTagExpression(tags);

console.log(tagExpression);
```

标记表达式消息可以使用以下代码发送:

```ts
import { NotificationHubsClient, createAppleNotification } from "@azure/notification-hubs";

const client = new NotificationHubsClient("<connection string>", "<hub name>");

const tagExpression = "likes_hockey && likes_football";
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;

const notification = createAppleNotification({
  body: messageBody,
  headers: {
    "apns-priority": "10",
    "apns-push-type": "alert",
  },
});

const result = await client.sendNotification(notification, { tagExpression });

console.log(`Tracking ID: ${result.trackingId}`);
console.log(`Correlation ID: ${result.correlationId}`);

// Only available in Standard SKU and above
if (result.notificationId) {
  console.log(`Notification ID: ${result.notificationId}`);
}
```

采用模块化方法,编码如下:

```ts
import { createClientContext, sendNotification } from "@azure/notification-hubs/api";
import { createAppleNotification } from "@azure/notification-hubs";

const context = createClientContext("<connection string>", "<hub name>");

const tagExpression = "likes_hockey && likes_football";
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;

const notification = createAppleNotification({
  body: messageBody,
  headers: {
    "apns-priority": "10",
    "apns-push-type": "alert",
  },
});

const result = await sendNotification(context, notification, { tagExpression });

console.log(`Tracking ID: ${result.trackingId}`);
console.log(`Correlation ID: ${result.correlationId}`);

// Only available in Standard SKU and above
if (result.notificationId) {
  console.log(`Notification ID: ${result.notificationId}`);
}
```

#### 预定发送

Push 通知可提前七天使用标准 SKU 命名空间及以上 `scheduleNotification` 用标签或一般广播发送设备的方法 `scheduleBroadcastNotification`。返回一个通知ID,必要时可通过 `cancelScheduledNotification` 方法.

```ts
import { NotificationHubsClient, createAppleNotification } from "@azure/notification-hubs";

const client = new NotificationHubsClient("<connection string>", "<hub name>");

const tagExpression = "likes_hockey && likes_football";
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;

// Schedule 8 hours from now
const scheduledTime = new Date(Date.now() + 8 * 60 * 60 * 1000);

const message = createAppleNotification({
  body: messageBody,
  headers: {
    "apns-priority": "10",
    "apns-push-type": "alert",
  },
});

const result = await client.scheduleNotification(scheduledTime, message, { tagExpression });

console.log(`Tracking ID: ${result.trackingId}`);
console.log(`Correlation ID: ${result.correlationId}`);

// Can be used to cancel via the cancelScheduledSend method
console.log(`Notification ID: ${result.notificationId}`);
```

采用模块化方法,编码如下:

```ts
import { createClientContext, scheduleNotification } from "@azure/notification-hubs/api";
import { createAppleNotification } from "@azure/notification-hubs";

const context = createClientContext("<connection string>", "<hub name>");

const tagExpression = "likes_hockey && likes_football";
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;

// Schedule 8 hours from now
const scheduledTime = new Date(Date.now() + 8 * 60 * 60 * 1000);

const message = createAppleNotification({
  body: messageBody,
  headers: {
    "apns-priority": "10",
    "apns-push-type": "alert",
  },
});

const result = await scheduleNotification(context, scheduledTime, message, { tagExpression });

console.log(`Tracking ID: ${result.trackingId}`);
console.log(`Correlation ID: ${result.correlationId}`);

// Can be used to cancel via the cancelScheduledSend method
console.log(`Notification ID: ${result.notificationId}`);
```

## 解决问题

## 反应原生支持

React Industrial 目前不支持 \[`URLSearchParams`由Azure通知中心SDK使用 为了在 React Industrial 中使用 SDK, 您需要安装 [`url-search-params-polyfill`](https://www.npmjs.com/package/url-search-params-polyfill) 软件包,并在使用 SDK 之前导入.

我们还需要提供多元填充 `TextEncoder` API 和 Aync 执行器 API. 请看我们的 [以 Expo 反应原生样本](https://github.com/Azure/azure-sdk-for-js/blob/main/samples/frameworks/react-native/appconfigBasic/README.md#add-polyfills) 更多细节.

### 已丢弃通知

Azure 通知中心有一个完整的指南, 用于解答已丢弃的通知的故障 [在 Azure 通知中心指南中解开通知](https://learn.microsoft.com/azure/notification-hubs/notification-hubs-push-notification-fixer)。 。 。 .

[测试发送](https://learn.microsoft.com/azure/notification-hubs/notification-hubs-push-notification-fixer#enabletestsend-property) 支持在 `sendNotification` 财务报告和审定财务报表 `sendBroadcastNotification` 方法与方法 `enableTestSend` 选项 :

```ts
import { NotificationHubsClient, createAppleNotification } from "@azure/notification-hubs";

const client = new NotificationHubsClient("<connection string>", "<hub name>");

const tagExpression = "likes_hockey && likes_football";
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;

const notification = createAppleNotification({
  body: messageBody,
  headers: {
    "apns-priority": "10",
    "apns-push-type": "alert",
  },
});

const result = await client.sendNotification(notification, {
  tagExpression,
  enableTestSend: true,
});
```

```ts
import { createClientContext, sendNotification } from "@azure/notification-hubs/api";
import { createAppleNotification } from "@azure/notification-hubs";

const context = createClientContext("<connection string>", "<hub name>");

const tagExpression = "likes_hockey && likes_football";
const messageBody = `{ "aps" : { "alert" : "Hello" } }`;

const notification = createAppleNotification({
  body: messageBody,
  headers: {
    "apns-priority": "10",
    "apns-push-type": "alert",
  },
});

const result = await sendNotification(context, notification, {
  tagExpression,
  enableTestSend: true,
});
```

### 日志

允许伐木可能有助于发现有关失败的有用信息。 为了查看 HTTP 请求和回复的日志,设置 `AZURE_LOG_LEVEL` 环境变量改为 `info`。或者,可以在运行时拨打 `setLogLevel` 输入 `@azure/logger`数字 :

```ts
import { setLogLevel } from "@azure/logger";

setLogLevel("info");
```

关于如何启用日志的更详细指示,您可以查看 [@ azure/ logger 包文件](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/core/logger)。 。 。 .

## 今后的步骤

以下样本显示您与 Azure 通知中心互动的各种方式:

**设备管理 :**

-   安装 API
    -   [创建或更新安装](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/notificationhubs/notification-hubs/samples-dev/createInstallation.ts)
    -   [更新安装](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/notificationhubs/notification-hubs/samples-dev/updateInstallation.ts)
-   登记 API
    -   [创建注册](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/notificationhubs/notification-hubs/samples-dev/createRegistration.ts)编号
    -   [创建或更新注册](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/notificationhubs/notification-hubs/samples-dev/createOrUpdateRegistration.ts)
    -   [更新注册](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/notificationhubs/notification-hubs/samples-dev/updateRegistration.ts)
    -   [清单登记](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/notificationhubs/notification-hubs/samples-dev/listRegistrations.ts)
    -   [以标签进行注册](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/notificationhubs/notification-hubs/samples-dev/listRegistrationsByTag.ts)

**发送操作 :**

-   [广播发送](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/notificationhubs/notification-hubs/samples-dev/sendBroadcastNotification.ts)
-   [直接发送](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/notificationhubs/notification-hubs/samples-dev/sendDirectNotification.ts)
-   [听众用标签发送列表](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/notificationhubs/notification-hubs/samples-dev/sendTagsList.ts)
-   [观众用标签表达式发送](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/notificationhubs/notification-hubs/samples-dev/sendTagExpression.ts)
-   [计划广播发送](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/notificationhubs/notification-hubs/samples-dev/scheduledSendBroadcastNotification.ts)
-   [预定发送](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/notificationhubs/notification-hubs/samples-dev/scheduledSendNotification.ts)

**管理业务:**

-   [出口登记](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/notificationhubs/notification-hubs/samples-dev/exportRegistrationsJob.ts)
-   [进口登记](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/notificationhubs/notification-hubs/samples-dev/importRegistrationsJob.ts)

## 捐款

如果您想为图书馆捐钱 请读一下 [贡献指南](https://github.com/Azure/azure-sdk-for-js/blob/main/CONTRIBUTING.md) 学习如何构建和测试密码.

这个模块的测试是现场测试和单位测试的混合,这需要您有一个Azure通知枢纽的例子. 执行测试需要运行:

1.  `pnpm install`
2.  `pnpm build --filter @azure/notification-hubs...`
3.  创建 .env 文件,其中包含这些内容 `sdk\notificationhubs\notification-hubs` 文件夹 : `NOTIFICATIONHUBS_CONNECTION_STRING=connection string for your Notification Hubs instance` `NOTIFICATION_HUB_NAME=Notification Hub name`
4.  `cd sdk\notificationhubs\notification-hubs`
5.  `npm run test`。 。 。 .

查看我们的 [测试](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/notificationhubs/notification-hubs/test) 详细文件夹.

## 相关项目

-   [微软 Azure SDK 用于 JavaScript](https://github.com/Azure/azure-sdk-for-js)
-   [Azure 通知中心](https://learn.microsoft.com/azure/notification-hubs/notification-hubs-push-notification-overview)

## 常见问题

### @azure/notification-hubs 是什么？

JavaScript 的 Azure 通知枢纽 SDK

### 如何安装 @azure/notification-hubs？

在项目目录运行 npm install @azure/notification-hubs，或使用 pnpm add / yarn add / bun add。

### @azure/notification-hubs 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @azure/notification-hubs 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @azure/notification-hubs 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=20\.0\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @azure/notification-hubs 可以商用吗？

@azure/notification-hubs 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @azure/notification-hubs 的下载量有多少？

根据 npm 官方下载统计，@azure/notification-hubs 在 2026/10/08 – 2026/11/06 这 30 天内被下载 83,205 次，日均约 2,774 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @azure/notification-hubs 还在维护吗？

最新版本 2\.1\.0 发布于 2026/05/06（6 个月前）；至今共发布 492 个版本，其中过去 12 个月发布了 68 个；首次发布于 2022/08/05。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

