NodeJS使用web-push推送消息

本文探讨了如何使用NodeJS服务端的web-push库实现Web Push API,以便即使在应用后台运行时也能向用户推送消息。介绍了创建工程、安装依赖以及在app.controller.ts和app.service.ts中的关键步骤。下篇将讲述Web端的service worker注册和endpoint提交。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Push API

The Push API gives web applications the ability to receive messages pushed to them from a server, whether or not the web app is in the foreground, or even currently loaded, on a user agent. This lets developers deliver asynchronous notifications and updates to users that opt in, resulting in better engagement with timely new content.

web应用接收来自server的消息,以往都是通过长连接或者轮训的方式获取。W3C Push API为Web应用接收来自server的消息提供了一种能力,不论Web程序是否在前台,我们都可以异步的向Web应用下发消息,就像原生APP那样。本文主要介绍NodeJS服务端使用web-push向web端发送消息,关于Push API的详细说明可查阅 MDN web dosc

web-push

使用web push功能推送消息到用户浏览器是比较复杂的,不仅需要以 web push协议向push service发送POST请求,而且header中需要VAPID信息以及对消息的加密信息。web-push 是一个实现web push消息推送的Node 库。

web push 服务

创建工程,安装依赖

新建node-webpush工程,使用NestJS框架:

nest new node-webpush
目录结构:
├── nest-cli.json
├── package.json
├── package-lock.json
├── README.md
├── src
│   ├── app.controller.spec.ts
│   ├── app.controller.ts
│   ├── app.module.ts
│   ├── app.service.ts
│   └── main.ts
├── test
│   ├── app.e2e-spec.ts
│   └── jest-e2e.json
├── tsconfig.build.json
└── tsconfig.json

安装web-push库:

npm i web-push -S

app.controller.ts

import {
   
    Body, Controller, Ip, Post, Query } from '@nestjs/common';
import {
   
    AppService } from './app.service';

@Controller()
export class AppController {
   
   
  constructor(private readonly appService: AppService) 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值