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

home2 게시판 Node.js, Express 게시판 채팅창 본인이 쓴 메시지 관련 질문

채팅창 본인이 쓴 메시지 관련 질문

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

    Chu
    참가자
    안녕하세요 채팅창에서 본인이쓴거는 오른쪽에 뜨게끔하는 기능을 구현하려고하는데
    제가생각한건 서버에서 유저아이디 받아온다음 본인이 쓴게 아니면 왼쪽에 본인이 쓴게 맞다면 오른쪽에
    나오게끔하려했는데 방식이 옳지않은건지 계속 오류떠서 질문드립니다.
    
    chat.ejs
     eventSource = new EventSource('/message/' + 지금누른채팅방id);
                    eventSource.addEventListener('test', function(e){
                        var 가져온거 = JSON.parse(e.data);
                        가져온거.forEach((i) => {
                            if(data[i]._id == user[i].id) {
                                $('.chat-content').append(`<li><span class="chat-box mine">${i.content}</span></li>`)
                            } else if(data[i]._id != user[i].id) {
                                $('.chat-content').append(`<li><span class="chat-box">${i.content}</span></li>`)
                            }
                            
                        });
                    })
    
    
    server.js
    app.get('/message/:id', loginStatus, (req, res) => {
        res.writeHead(200, {
            "Connection": "keep-alive",
            "Content-Type": "text/event-stream",
            "Cache-Control": "no-cache",
        });
        db.collection('message').find({ parent: req.params.id }).toArray().then((result) => {
            res.write('event: test\n');
            res.write(`data: ${JSON.stringify(result)}\n\n`);
            res.send( {user : req.user}, {data : req.body} )
        });
        const pipeline = [
            { $match : { 'fullDocument.parent': req.params.id } }
        ];
        const collection = db.collection('message');
        const changeStream = collection.watch(pipeline);
        changeStream.on('change', (result) => {
            res.write('event: test\n');
            res.write(`data: ${JSON.stringify([result.fullDocument])}\n\n`);
        });
    })
    #60604

    codingapple
    키 마스터
    어떤오류입니까
    #60727

    Chu
    참가자
    express deprecated res.send(status, body): Use res.status(status).send(body) instead server.js:331:13
    node:internal/errors:484
        ErrorCaptureStackTrace(err);
        ^
    
    Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
        at new NodeError (node:internal/errors:393:5)
        at ServerResponse.setHeader (node:_http_outgoing:644:11)
        at ServerResponse.header (경로\codingapple\TodoApp\node_modules\express\lib\response.js:794:10)
        at ServerResponse.send (경로\codingapple\TodoApp\node_modules\express\lib\response.js:174:12)
        at ServerResponse.json (경로\codingapple\TodoApp\node_modules\express\lib\response.js:278:15)
        at ServerResponse.send (경로\codingapple\TodoApp\node_modules\express\lib\response.js:162:21)
        at 경로\codingapple\TodoApp\server.js:331:13
        at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
      code: 'ERR_HTTP_HEADERS_SENT'
    
    라고뜨고 챗룸에서 채팅방 클릭하면 채팅자체가 안떠버리네요
    #60729

    codingapple
    키 마스터
      res.send 는 지웁시다
4 글 보임 - 1 에서 4 까지 (총 4 중에서)
  • 답변은 로그인 후 가능합니다.

About

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

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

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