웹개발

[React] SSE로 프론트엔드 쪽 코드 구현할때, 헤더(Authorization 등)설정하기 (feat. event-source-polyfill)

Heeyeon Choi 2024. 8. 20. 20:39
728x90

SSE (Server-Sent events)?

서버에서 클라이언트로 실시간 이벤트를 전달하는 웹 기술입니다.

- 보통의 HTTP 통신 : 요청 1번 응답 1번 입니다.

- SSE(Server-Sent events) : 한번의 연결로 여러번의 응답을 실시간으로 받을 수 있습니다.

서버에서 클라이언트로의 단방향 스트리밍

 

EventSource

:SSE 연결을 편리하게 할 수 있도록 해주는 Web API입니다.

 

실제로 SSE 구현해보기

EventSource 는 헤더 설정이 불가능합니다. 따라서 event-source-polyfill 패키지의 도움을 받아야 합니다.

event-source-polyfill

: 이 라이브러리는 표준 EventSource를 폴리필로 제공하여, 추가적인 기능(예: 헤더 설정)을 지원합니다.

import React, { useState, useEffect } from 'react';
import { EventSourcePolyfill, NativeEventSource } from "event-source-polyfill";
function App() {
  const [events, setEvents] = useState([]);

  useEffect(() => {
    console.log("켜짐");
    const EventSource = EventSourcePolyfill || NativeEventSource;
    // 프록시 서버 URL로 EventSource 설정
    const eventSource = new EventSource('https://mk-blogservice.site/api/notifications/stream',{
      headers: {
        Authorization: sessionStorage.getItem('accessToken')
      },
      withCredentials: true,
    
    });

    console.log('EventSource initialized:', eventSource);

    eventSource.onmessage = function(event) {
      try {
        console.log('Event received:', event);
        const newEvent = JSON.parse(event.data);
        setEvents(prevEvents => [...prevEvents, newEvent]);
      } catch (err) {
        console.error('Error parsing event data:', err);
      }
    };

    eventSource.onerror = function(err) {
      console.error("EventSource failed:", err);
      eventSource.close();
    };

    return () => {
      console.log('Closing EventSource');
      eventSource.close();
    };
  }, []);

  return (
    <div>
      
    </div>
  );
}

export default App;
728x90