Axios를 사용하여 클라이언트 측에서 모바일 알림 전송하기

이번 포스트에서는 Axios를 사용하여 클라이언트 측에서 모바일 알림을 전송하는 방법에 대해 알아보겠습니다. Axios는 브라우저와 Node.js에서 모두 사용할 수 있는 간편한 HTTP 클라이언트 라이브러리입니다.

Axios 설치하기

먼저, Axios를 설치해야 합니다. npm을 사용하면 간단하게 설치할 수 있습니다.

npm install axios

모바일 알림 전송하기

모바일 알림을 전송하기 위해서는 서버 측에 API 엔드포인트가 필요합니다. 이 예제에서는 Firebase Cloud Messaging(FCM)을 사용하여 모바일 알림을 전송하는 방법을 보여줄 것입니다.

import axios from 'axios';

const sendMobileNotification = async (notificationData) => {
  try {
    const response = await axios.post('https://fcm.googleapis.com/fcm/send', notificationData, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer YOUR_FCM_SERVER_KEY',
      },
    });

    console.log('Notification sent successfully:', response.data);
  } catch (error) {
    console.error('Failed to send notification:', error);
  }
};

const notificationData = {
  to: 'DEVICE_TOKEN',
  notification: {
    title: 'New Message',
    body: 'You have a new message.',
  },
};

sendMobileNotification(notificationData);

위의 코드에서 YOUR_FCM_SERVER_KEYDEVICE_TOKEN을 실제 값으로 대체해야 합니다. YOUR_FCM_SERVER_KEY는 Firebase 콘솔에서 찾을 수 있으며, DEVICE_TOKEN은 클라이언트 측에서 등록한 기기의 토큰입니다.

결론

Axios를 사용하여 클라이언트 측에서 모바일 알림을 전송하는 방법을 살펴보았습니다. 이를 통해 간편하게 HTTP 요청을 처리하고, 서버와 통신하여 모바일 알림을 전송할 수 있습니다. Firebase Cloud Messaging과의 통합을 통해 더욱 다양한 기능을 구현할 수 있으니, 참고하셔서 유용하게 사용해보시기 바랍니다.

References