通过GCM在Progressive web应用程序中推送通知

Push notifications in Progressive web app through GCM

本文关键字:通知 应用程序 web GCM Progressive 通过      更新时间:2023-09-26

在发送推送通知时,我收到了(Uncaught(in promise)ReferenceError:require is not defined(…))错误。这是我的代码

 const endPoint = subscription.endpoint.slice(subscription.endpoint.lastIndexOf('/')+1);
console.log(endPoint);
var gcm = require('node-gcm');
var message = new gcm.Message({
    notification: {
        title: "Hello, World",
        icon: "ic_launcher",
        body: "This is a notification that will be displayed ASAP.",
        tag:"hello"
    }
});
var regTokens = [endPoint];
  var sender = new gcm.Sender('AIzaSyD9Bcxd_MQZFoGjO1y_hPm-xUdgnM25Ny4'); //API Key
  // Now the sender can be used to send messages
  sender.send(message, { registrationTokens: regTokens }, function (error, response) {
   if (error) {
      console.error(error);
      res.status(400);
    }
   else {
      console.log(response);
      res.status(200);
    }
  });
      })
    })
}

错误屏幕截图在此处输入图像描述

此代码使用require,因此在我看来,您正试图在浏览器中使用节点代码。要做到这一点,您需要使用类似Browserify的东西,尽管我不确定这是否适用于node-gcm,因为它可能对发送无跨源限制的网络请求有某些要求。