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

home2 게시판 Node.js, Express 게시판 유저간 채팅기능 5 질문

유저간 채팅기능 5 질문

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

    이창민
    참가자
    TypeError: Cannot read properties of undefined (reading '_id')
    
    해당 에러가 뜨는 이유가 해석이 안됩니다ㅠㅠ
    
    왜뜨는건가욤
    어디가 틀린건지 ㅠㅠ
    
    //채팅기능
      app.post('/chatroom', 로그인했니, function(요청, 응답){
        var 저장할거 = {
          title : '무슨무슨채팅방',
          member : [ObjectId(요청.body.당한사람id), 요청.user._id],
          date : new Date()
        }
        db.collection('chatroom').insertOne(저장할거).then((결과)=>{
          응답.send('성공')
        })
      })
      app.get('/chat', function(요청, 응답){
        db.collection('chatroom').find({ member : 요청.user._id }).toArray().then((결과)=>{
          응답.render('chat.ejs', { data : 결과 })
        })
      })
      app.post('/message', 로그인했니, function(요청, 응답){
        var 저장할거 = {
          parent : 요청.body.parent,
          content : 요청.body.content,
          userid : 요청.user._id,
          date : new Date(),
        }
        db.collection('message').insertOne(저장할거).then(()=>{
          console.log('DB저장성공')
          응답.send('DB저장성공')
        })
      })
      app.get('/message/:id', 로그인했니, function(요청, 응답){
        응답.writeHead(200, {
          "Connection": "keep-alive",
          "Content-Type": "text/event-stream",
          "Cache-Control": "no-cache",
        });
      
        db.collection('message').find({ parent : 요청.params.id }).toArray().then((결과)=>{
          응답.write('event: test\n');
          응답.write('data: ' + JSON.stringify(결과) + '\n\n');
        })
        const pipeline = [
          { $match: { 'fullDocument.parent' : 요청.params.id } }
        ];
        const collection = db.collection('message');
        const changeStream = db.collection.watch(pipeline);
        changeStream.on('change', (result) => {
          응답.write('event: test\n');
          응답.write('data: ' + JSON.stringify([result.fullDocument]) + '\n\n');
        });
      });
    
    
    -----------------------
    
    
    <script>
          var 지금누른채팅방id;
          var eventSource;
          $('.list-group-item').click(function(){
            지금누른채팅방id = this.dataset.id;
            $('.chat-content').html('');
            if(eventSource != undefined){
              eventSource.close()
            }
          eventSource = new EventSource('/message' + 지금누른채팅방id)
          eventSource.addEventListener('test', function(e){
            var 가져온거 = JSON.parse(e.data);
            가져온거.forEach(function(i){
              $('.chat-content').append('
  • <span class="chat-box">' + i.content + '</span>
  • ')         })         })       })
          $('#send').click(function(){
            var 채팅내용 = $('#chat-input').val();
            var 보낼거 = {
              parent : 지금누른채팅방id,
              content : 채팅내용,
            }
            $.post('/message', 보낼거).then(()=>{
              console.log('전송성공')
            })
          })
        </script>
    #54757

    이창민
    참가자
    app.get('/message/:id', 로그인했니, function(요청, 응답){
    
    저기가 틀렸다는데 왜 틀린건지 모르겠습니다 ㅠ
    #54784

    codingapple
    키 마스터
    _id 왼쪽이 텅비어있다는 뜻이라 요청.user 있나 확인하면 됩니다 
    로그인안하면 그럴수도요
    #54792

    이창민
    참가자
      app.get('/message/:id'
    부분은 :parentid가 아니라 그냥 id맞나요
    #54818

    codingapple
    키 마스터
    넴 밑에서 params.id 라고 쓰고싶으면 :id라고 쓰고 
    params.parentid라고 쓰고싶으면 :parentid라고 쓰면 됩니다
5 글 보임 - 1 에서 5 까지 (총 5 중에서)
  • 답변은 로그인 후 가능합니다.

About

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

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

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