트러블 슈팅
[React+Typescript]EventSourece에 header 담기
워딩이
2023. 9. 5. 12:41
문제 발생
리액트로 SSE 구현 중에 엑세스 토큰을 header에 담아서 보내야하는데, EventSource에서 headers를 넣을 수 없다는 오류가 발생했다.
'EventSourceInit'형식에 'headers'이(가) 없습니다.
원인 해결
EventSourcePolyfill 라이브러리를 이용해서 header 부분에 담을 수 있게 설정을 해주었다. 사용 방법은 아래와같다.
const EventSource = EventSourcePolyfill || NativeEventSource;
최종
const EventSource = EventSourcePolyfill || NativeEventSource;
useEffect(() => {
if (!isLoading && getToken) {
const fetchSse = async () => {
try {
const sse = new EventSource(
`URL`,
{
hearders:{
//headers에 들어가는 부분
},
withCredentials: true,
},
);
sse.onmessage = async (e) => {
console.log('데이터입니다', e);
};
sse.onerror = async (e) => {
console.log('에러입니다', e);
sse.close();
};
} catch (error) {}
};
fetchSse();
}
}, []);