将消息从NodeJS服务器发送到Web客户端

时间:2017-11-17 13:27:53

标签: javascript firebase firebase-cloud-messaging

我正在尝试将消息从我的服务器发送到客户端,但无法使其正常工作(永远不会调用onMessage处理程序。)

chrome://gcm-internals/选项卡中,每当我运行服务器代码时,我都可以看到消息进入。这意味着服务器和浏览器之间的连接正常。问题必须出在客户端代码中。

enter image description here

以下是一般流程:

  • 客户端代码(伪代码)连接到firebase,获取token, 订阅onMessage事件。

  • 服务器代码(伪代码)使用客户端令牌连接到firebase发送payload到客户端

客户代码:

import firebase from 'firebase/app'
require('firebase/messaging')
import { serviceWorkerRegistration } from './worker.service'

const config = {
  apiKey: <...>,
  authDomain: <...>,
  databaseURL: <...>,
  projectId: <...>,
  storageBucket: <...>,
  messagingSenderId: <...>
}

const app = firebase.initializeApp(config)
const messaging = firebase.messaging()

messaging.useServiceWorker(serviceWorkerRegistration)

messaging.getToken()
  .then(token => console.log(token)
  .catch(error => console.log(error))

messaging.onMessage(function (payload) {
  console.log('Message received:', payload)
})

服务器代码:

const admin = require('firebase-admin')
const config = require('./config')
const signature = require('./signature.json')

admin.initializeApp({
  credential: admin.credential.cert(signature),
  databaseURL: config.databaseURL
})

const messaging = admin.messaging()

const token = <...>

const payload = {
  data: {
    text: "Hello from server"
  }
}

admin.messaging().sendToDevice(token, payload)
  .then(function(response) {
    console.log('response:',response)
    console.log('response.results:',response.results)
  })
  .catch(function(error) {
    console.log("Error sending message:", error)
  })

正如我从docs了解到的那样,当应用程序位于foreground时,此设置可以处理传入消息,但由于某种原因,它不起作用。我错过了什么?

1 个答案:

答案 0 :(得分:0)

显然,要使通知和消息正常工作,必须在messaging文件中启动service worker

service-worker.js(摘录)

importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js')
firebase.initializeApp({ messagingSenderId: <...> })
const messaging = firebase.messaging()

messaging.setBackgroundMessageHandler(function (payload) {
  console.log(payload)
  const title = payload.data.title
  const options = {
    body: payload.data.title,
    icon: '/notification-icon-192.png'
  }
  return self.registration.showNotification(title, options)
})