Branch merge 후 채팅 BE 코드 문제 해결

프론트에서 response를 제대로 받아오지 못하는 오류 발견

SuccessResponse <>() 안에 담아서 response 전달하는 방법으로 해결

@MessageMapping("/{categoryId}/send")
    @SendTo("/{categoryId}/paging")
    public SuccessResponse<Chatlog>  handleWebSocketChat(@DestinationVariable int categoryId, @Payload Chatlog chatlog) {
        chatService.saveChatlog(chatlog); // DB에 저장
        return new SuccessResponse<>(chatlog); // WebSocket을 통해 다른 클라이언트에 전송
    } //ChatRoomPage에 있는 ChatInputFrom component에서 요청을 하면 받는 곳

채팅 FE 페이지, 컴포넌트, axios 구현

  1. page
    1. ChatListPage

      • Footer로 연결되는 페이지.
      • 각 카테고리 별로 ChatPreview 컴포넌트 포함.
      return (
        <div className="h-[calc(100%_-_64px)] text-white">
          <div>
            <ul>
                {categories.map((category) => (
                  <li key={category.categoryId} className="p-4 bg-white shadow-md mb-2 rounded-lg">
                    <h2>{category.categoryName} 채팅방</h2>
                    <ChatPreview categoryId={category.categoryId}/>
                  </li>
                ))}
              </ul>
          </div>  
        </div>
        );
      
    2. ChatRoomPage

      • ChatPreview 컴포넌트와 연결된 버튼을 통해 연결되는 페이지.
      • Chatlog, ChatInput 컴포넌트 포함.
  2. Component
    1. ChatPreview

      • 최신 채팅 (최대) 5개 조회.
      • 채팅로그를 조회하여 채팅이 없는 경우, 아직 해당 카테고리 채팅방에 대한 WebSocket이 존재하지 않는다고 간주하여 WebSocket 연결 시도.
      useEffect(() => {
              const fetchChatPreviews = async () => {
                  try {
                      const socket = new WebSocket('ws://localhost:5173/');
                      const response = await ChatApi.preview(categoryId);
      
                      if (response.data.length === 0) {
                          const stomp = Stomp.over(socket);
                          
                          setStompClient(stomp); // Stomp 클라이언트 설정
                          stompClient.activate();
                      } else {
                          setChatPreviews(response.data);
                      }
                  } catch (error) {
                      console.log("채팅 미리보기 화면에 접근 불가", error);
                  } 
              };
      
              fetchChatPreviews();
          }, [categoryId]);
      
          const onConnected = () => {
              console.log("WebSocket 연결됨");
          };
      
          const onError = (error) => {
              console.log("WebSocket 연결 오류", error);
          };
      
          const navigateToChatRoom = () => {
              if (stompClient) {
                  navigate(`/chat/${categoryId}/paging`);
              } else {
                  console.log("웹소켓 연결을 아직 기다리는 중입니다.");
              }
          };
      
      • 현재 WebSocket 연결 시도에 대한 에러 수정 중. fetchChatPreviews 에서 에러 로그가 찍힘.
    2. Chatlog

      • 최신 채팅 (최대) 10개 조회.
      • 스크롤 이벤트를 통해 새로운 채팅 로그 10개를 불러오고, 기존에 불러온 채팅 페이지 저장하는 기능 구현 중. WebSocket 연결 완료 후 해결할 예정.
      useEffect(() => {
              const fetchMoreChatlog = async () => {
                  if (loading) return;
                  setLoading(true);
      
                  try {
                      const response = await ChatApi.chatRoom(categoryId, page);
                      setChatlog((prevChatlog) => [...prevChatlog, ...response.data]);
                      setPage(prevPage => prevPage + 1);
                  } catch (error) {
                      console.error(error);
                  } finally {
                      setLoading(false);
                  }
              };
      
              const handleScroll = () => {
                  // 스크롤 이벤트 로직 (예: 페이지 맨 위에 도달했을 때 새 로그 불러오기)
                  if (window.scrollY === 0) {
                      fetchMoreChatlog();
                  }
              };
      
              window.addEventListener("scroll", handleScroll);
              return () => window.removeEventListener("scroll", handleScroll);
          }, [page, loading, categoryId]);
      
    3. ChatInput

      • 채팅 작성 form 및 전송.
      • 전송 버튼 클릭 시 (상위) ChatRoomPage의 handleSend 함수를 실행.
  3. Axios
    1. chat-axios
      • ChatApi 내에 chatList, preview, chatRoom, sendChatlog 작성하여 BE ChatlogController와 연결 완료.
    2. websocket
      • websocket에서 처리하는 기능들을 따로 정리.
      • 해당 파일로 분리시킬지, ChatPreview에서 webSocket을 처리할지 고민하는 과정.
      • WebSocket 연결에 문제가 있어서 해결하는 과정, SockJS와 STOMP를 함께 사용하면서 개념적으로 오류가 발생하고 있는 것 같아 이 부분 가장 우선순위로 잡고 해결 중.

발생한 문제

global is not defined

⇒ App.jsx 에서 아래 코드 추가 후 해결됨

if (typeof window !== 'undefined' && typeof window.global === 'undefined') {
    window.global = window;
  }

websocket is closed before the connection is established

GET 404, POST 404 에러 발생

ChatListPage의 ChatPreview 에 대해 버튼 클릭 시 (주소는 이동 했는데) ChatRoomPage로 화면이 이동하지 않음