通过GCM在渐进式Web应用程序中推送通知

问题描述:

在发送推送通知时,我收到了(未捕获(承诺)ReferenceError:未定义require(…))错误.这是我的代码

while sending push notification i got ( Uncaught (in promise) ReferenceError: require is not defined(…)) error.here is my code

 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 之类的方法,尽管我不确定这是否适用于可能对发送网络请求有一定的要求,而没有跨源限制等.

This code uses require, so it looks to me like you're trying to use node code in the browser. To do that you'll need to use something like Browserify, although I'm not sure that's going to work for node-gcm as it may have certain requirements about sending network requests without cross origin restrictions etc.