【问题标题】:Why am I getting "Error: No key set vapidDetails.publicKey"?为什么我收到“错误:没有密钥集 vapidDetails.publicKey”?
【发布时间】:2020-08-14 23:45:46
【问题描述】:

我正在尝试为推送通知运行“node.js”服务器。但我收到了一个错误。这是在使用 SwPush 到 Angular 上的 PWA 添加推送通知的教程中得到的。

我需要将公钥放在某个地方吗?我使用“web-push generate-vapid-keys”生成了公钥和私钥。

Server.js 脚本:

    // server.js
require('dotenv').config({ path: 'variables.env' });

const express = require('express');
const cors = require('cors')
const webPush = require('web-push');
const bodyParser = require('body-parser');

const app = express();

app.use(cors());

app.use(bodyParser.json());

const publicVapidKey = process.env.PUBLIC_VAPID_KEY;
const privateVapidKey = process.env.PRIVATE_VAPID_KEY;

webPush.setVapidDetails('mailto:test@example.com', publicVapidKey, privateVapidKey);

app.post('/notifications', (req, res) => {
  const subscription = req.body.notification;

  console.log(`Subscription received`);

  res.status(201).json({});

  const payload = JSON.stringify({
    notification: {
      title: 'Notifications are cool',
      body: 'Know how to send notifications through Angular with this article!',
      icon: 'https://www.shareicon.net/data/256x256/2015/10/02/110808_blog_512x512.png',
      vibrate: [100, 50, 100],
      data: {
        url: 'https://medium.com/@arjenbrandenburgh/angulars-pwa-swpush-and-swupdate-15a7e5c154ac'
      }
    }
  });

  webPush.sendNotification(subscription, payload)
    .catch(error => console.error(error));
});

app.set('port', process.env.PORT || 5000);
const server = app.listen(app.get('port'), () => {
    console.log(`Express running → PORT ${server.address().port}`);
});

【问题讨论】:

    标签: node.js angular server push-notification progressive-web-apps


    【解决方案1】:

    在你的第 1 行:

    require('dotenv').config({ path: 'variables.env' });
    

    上面的代码从一个名为 variables.env 的文件中获取您的信息,该文件不是您创建的; 因此,要实现这一点,请创建一个名为 variables.env 的文件并将所有环境变量放在那里

    为了让它直接从 .env 文件中获取您的信息,请将第 1 行中的代码更改为:

    require('dotenv').config();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多