3 글 보임 - 1 에서 3 까지 (총 3 중에서)
-
글쓴이글
-
2023년 2월 8일 23:57 #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 이런 에러가뜨던데..
제가 코드를 너무 거지같이짠건가요?
2023년 2월 9일 00:23 #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)); }); }); }); }); 이런식으로바꿔줫더니 일단은 잘되는데.. 채팅을 치고, 지우고 다시 입력하면 동작이 꼬인다고해야할까요? ..역시 제가 코드를 어디서 실수한걸까요?
2023년 2월 9일 09:42 #67537
codingapple키 마스터삭제누르면 다시 이벤트리스너 부착하고 그럴 필요는 없어보입니다 1. 서버로 삭제요청하고 2. 클릭한 html도 안보이게 숨겨주고 이정도만 해도 될듯요
-
글쓴이글
3 글 보임 - 1 에서 3 까지 (총 3 중에서)
- 답변은 로그인 후 가능합니다.