FCM的成功回复但没有通知

时间:2018-04-08 17:15:31

标签: javascript firebase push-notification firebase-cloud-messaging progressive-web-apps

在客户端,我请求权限并将令牌发送到服务器

messaging.requestPermission()
.then(function() {
    console.log('Notification permission granted.');
    return messaging.getToken();
})
.then((token) => {
    if (token) {
        const body = JSON.stringify({
            token,
            stopId: 'BKK_F02550',
            routeId: 'BKK_0205',
        });
        const headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        };
        console.log(token, 'token');
        fetch('/api/test', {method: 'post', body, headers});
    } else {
        console.log('No Instance ID token available. Request permission to generate one.');
    }
})
.catch(function(err) {
    console.log('Unable to get permission to notify.', err);
});

在服务器端,我将请求发送给FCM:

app.post('/api/test', (req, res) => {
    const body = {
        "to": req.body.token,
        "notification":{
            "title":"Portugal vs. Denmark",
            "body":"great match!"
        }
    }

    const headers = {
        Authorization: `key=${serverKey}`,
        'Content-Type': 'application/json'
    }

    fetch('https://fcm.googleapis.com/fcm/send', body, headers)
        .then(data => res.status(200).json(data))
        .catch(error => console.log('failure', error))
})

我收到成功回复,但我没有收到客户端的通知。我觉得响应对象的要点是:{size:0,timeout:0}。

1 个答案:

答案 0 :(得分:0)

我不确定,但我认为您的客户端代码存在顺序问题。随着return messaging.getToken()返回;永远不会超过剩余的代码,你会看到,我试图在下面进行重组。 (我不确定下一个问题,但会检查后)。

messaging.requestPermission()
.then(function() {
    console.log('Notification permission granted.');
    .then((token) => {
          if (token) {
              const body = JSON.stringify({
                  token,
                  stopId: 'BKK_F02550',
                  routeId: 'BKK_0205',
              });
              const headers = {
                  'Accept': 'application/json',
                  'Content-Type': 'application/json',
              };
              console.log(token, 'token');
              fetch('/api/test', {method: 'post', body, headers});
          } else {
              console.log('No Instance ID token available. Request permission to generate one.');
          }
      })
   return messaging.getToken();
 })
.catch(function(err) {
    console.log('Unable to get permission to notify.', err);
});