• 로그인
  • 장바구니에 상품이 없습니다.

home2 게시판 Node.js, Express 게시판 선생님 메시지 삭제 이런식으로 구현하면될까요?

선생님 메시지 삭제 이런식으로 구현하면될까요?

3 글 보임 - 1 에서 3 까지 (총 3 중에서)
  • 글쓴이
  • #67505

    정중식
    참가자
    클라이언트 코드입니다.
    
      $('.list-group-item').click(function (e) {
        $(this).css('background-color', '#eee');
        nowChatRoomId = $(this).attr('data-id');
        $('.chat-content').html('');
        // 프론트엔드에서 실시간 소통채널 여는법
        eventSource = new EventSource('/message/' + nowChatRoomId);
        eventSource.addEventListener('test', function (e) {
          var data = JSON.parse(e.data);
          data.forEach((item) => {
            $('.chat-content').append(
              `<li class='box-wrap' data-id=${item._id}><span class="chat-box mine">${item.content}</span></li>`
            );
          });
          // 삭제구현
          const boxWrap = document.querySelectorAll('.box-wrap');
          boxWrap.forEach((box) => {
            box.addEventListener('click', function (e) {
              messageId = e.currentTarget.dataset.id;
              fetch(`/message/delete/${nowChatRoomId}/${messageId}`, {
                method: 'DELETE',
              }).then((data) => console.log(data));
            });
          });
        });
      });
     
    
    서버 코드입니다.
    
    
    app.delete(
      '/message/delete/:parentid/:messageid',
      isLogin,
      function (req, res) {
        res.writeHead(200, {
          Connection: 'keep-alive',
          'Content-Type': 'text/event-stream',
          'Cache-Control': 'no-cache',
        });
        
        db.collection('message')
          .deleteOne({ _id: ObjectId(req.params.messageid) })
          .then((result) => {
            console.log('삭제완료');
            db.collection('message')
              .find({ parent: req.params.parentid })
              .toArray()
              .then((result) => {
                res.write('event: test\n');
                res.write(`data: ${JSON.stringify(result)}\n\n`);
              });
          });
        const pipeline = [
          { $match: { 'fullDocument.parent': req.params.parentid } },
        ];
        const changeStream = db.collection('message').watch(pipeline);
        changeStream.on('change', (result) => {
          var addData = [result.fullDocument];
          res.write('event: test\n');
          res.write(`data: ${JSON.stringify(addData)}\n\n`);
        });
      }
     
    
    클라이언트 코드에서 삭제후에     eventSource = new EventSource();를 써서 서버와 실시간소통창구를 또 열어주면되나요?
    근데 이런식으로해봤는데 계속Cannot set headers after they are sent to the client 이런 에러가뜨던데..
    제가 코드를 너무 거지같이짠건가요?
     
    #67507

    정중식
    참가자
    서버코드
    
    
    app.get('/message/delete/:parentid/:messageid', isLogin, function (req, res) {
      res.writeHead(200, {
        Connection: 'keep-alive',
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
      });
      db.collection('message')
        .deleteOne({ _id: ObjectId(req.params.messageid) })
        .then((result) => {
          console.log('삭제완료');
          db.collection('message')
            .find({ parent: req.params.parentid })
            .toArray()
            .then((result) => {
              res.write('event: test\n');
              res.write(`data: ${JSON.stringify(result)}\n\n`);
            });
        });
      const pipeline = [{ $match: { 'fullDocument.parent': req.params.parentid } }];
      const changeStream = db.collection('message').watch(pipeline);
      changeStream.on('change', (result) => {
        var addData = [result.fullDocument];
        res.write('event: test\n');
        res.write(`data: ${JSON.stringify(addData)}\n\n`);
      });
     
    
    클라코드
    
    
      var nowChatRoomId;
      var messageId;
      var eventSource;
      var boxWrap;
      $('.list-group-item').click(function (e) {
        $(this).css('background-color', '#eee');
        nowChatRoomId = $(this).attr('data-id');
        $('.chat-content').html('');
        // 프론트엔드에서 실시간 소통채널 여는법
        eventSource = new EventSource('/message/' + nowChatRoomId);
        eventSource.addEventListener('test', function (e) {
          var data = JSON.parse(e.data);
          data.forEach((item) => {
            $('.chat-content').append(
              `<li class='box-wrap' data-id=${item._id}><span class="chat-box mine">${item.content}</span></li>`
            );
          });
          boxWrap = document.querySelectorAll('.box-wrap');
          // 삭제구현
          boxWrap.forEach((box) => {
            box.addEventListener('click', function (e) {
              messageId = e.currentTarget.dataset.id;
              eventSource = new EventSource(
                `/message/delete/${nowChatRoomId}/${messageId}`
              );
              eventSource.addEventListener('test', function (e) {
                var data = JSON.parse(e.data);
                $('.chat-content').html('');
                data.forEach((item) => {
                  $('.chat-content').append(
                    `<li class='box-wrap' data-id=${item._id}><span class="chat-box mine">${item.content}</span></li>`
                  );
                });
              });
              // fetch(`/message/delete/${nowChatRoomId}/${messageId}`, {
              //   method: 'DELETE',
              // }).then((data) => console.log(data));
            });
          });
        });
      });
     
    
    이런식으로바꿔줫더니 일단은 잘되는데..
    채팅을 치고, 지우고 다시 입력하면 동작이 꼬인다고해야할까요? ..역시 제가 코드를 어디서 실수한걸까요?
    #67537

    codingapple
    키 마스터
    삭제누르면 다시 이벤트리스너 부착하고 그럴 필요는 없어보입니다
    1. 서버로 삭제요청하고
    2. 클릭한 html도 안보이게 숨겨주고
    이정도만 해도 될듯요
3 글 보임 - 1 에서 3 까지 (총 3 중에서)
  • 답변은 로그인 후 가능합니다.

About

현재 월 700명 신규수강중입니다.

  (09:00~20:00) 빠른 상담은 카톡 플러스친구 코딩애플 (링크)
  admin@codingapple.com
  이용약관
ⓒ Codingapple, 강의 예제, 영상 복제 금지
top

© Codingapple, All rights reserved. 슈퍼로켓 에듀케이션 / 서울특별시 강동구 고덕로 19길 30 / 사업자등록번호 : 212-26-14752 온라인 교육학원업 / 통신판매업신고번호 : 제 2017-서울강동-0002 호 / 개인정보관리자 : 박종흠