BackEnd/Nodejs

[node.js] NODEJS-FCM 알림

cdjiwon 2022. 8. 4. 18:22

기존에 진행하고 있는 졸업작품에 앱에 알림을 띄워주기 위해서 따로 Firebase의 Notification을 구상하기로 했다.

 

알림이 쓰이는 곳은 크게 두 가지이다.

1. 공지사항 작성 후 push 버튼을 눌러 알림 보내기

2. AI 분석 서버에서 해당되는 Data 값에 맞게 알림 보내기

동작 방식

node-andorid fcm

Firebase 설정

1. Firebase 회원 가입

2. 프로젝트 추가

3. 애널리틱스 설정

4. 애널리틱스 구성

5. Firebase 앱 내부 화면

6. [프로젝트 설정] - [서비스 계정]

여기까지 진행하면 서버에서 앱과 통신하기 위한 Firebase 설정이 끝난다.

 

Node.js

1. [Config] - [pushConn.js]

const adminAndroid = require('firebase-admin');

# 이전 firebase 설정으로 받았던 비공개키의 위치를 넣어줌
let androidServiceAccount = require('서비스계정키.json')

const admin = adminAndroid.initializeApp({
	credential : adminAndroid.credential.cert(androidServiceAccount)
    });
    
module.exports = admin;

2. [Route] - [notice.js]

const express = require('express');
const router = express.Router();
const noticeCtrl = require('../controller/noticeCtrl');

router.get('/send', noticeCtrl.pushNotice);

module.exports = router;

3. [Controller] - [noticeCtrl.js]

const noticeDAO = require('../model/noticeDAO')
const admin = require('../config/pushConn');

const pushNotice = async (req, res) => {
	const parameters = {
    	"notice_num" : req.query.num
        }
   	const result = await noticeDAO.read_notice(parameters);
    
    // fcm send message 
    let message = {
    	token : '안드로이드 token값',
        notification : {
        // 보내는 위치 알려주기 위해 body에 Notice 넣어줌
        	body : "Notice"
            },
       	data : {
        	title : result[0].notice_title,
            body : result[0].notice_content
            },
     	android : {
			priority : "high",
            },
     	}
        
        admin.messaging()
        	.send(message)
            .then((res) => {
            	console.log('Success sent message : ', res);
                res.send(res);
          	})
            .catch((err) => {
            	console.log('Error Sending message !! : ', err);
                res.send(err);
          	})
};

이러면 서버 코드 작성을 끝낼 수 있다.

 

이후 postman으로 결과를 확인해보자.

- send의 query 값을 줘야 DB에 접속 가능하기 때문에 queryString으로 num=1을 전송했다.

- Android에 설정이 잘 되어있다면 메시지 보낸 값들을 json 형식으로 받을 수 있다.

 

git : https://github.com/Capstone-Bubba/Bubba

 

GitHub - Capstone-Bubba/Bubba: Capstone_Team Project

Capstone_Team Project. Contribute to Capstone-Bubba/Bubba development by creating an account on GitHub.

github.com

 

'BackEnd > Nodejs' 카테고리의 다른 글

Sokcet.io + 간단한 실시간 채팅 구현  (1) 2022.08.04
웹 통신 방식의 변화  (0) 2022.08.04
Node.js 시작하기  (0) 2022.05.16