-
글쓴이글
-
2022년 4월 4일 00:55 #31038
Eric참가자회원 실시간 채팅기능 구현간에 채팅방을 클릭하면 각 채팅방에 남겼던 글들이 나와야하는데
EventSource 로드하지 못함: GET "http://localhost:8070/message/6249c00094d3d284d815838c".
이렇게 뜨는거같긴한데.. 어디가 잘못된걸까요?
server.js
app.post('/message',isLogin,function(req,res){
var wantSave = {
parent: ObjectId(req.body.parent),
content: req.body.content,
userid: req.user._id,
date: new Date(),
}
db.collection('message').insertOne(wantSave).then(()=>{
console.log('DB저장성공');
res.send('DB저장성공!');
})
});app.get('/message/:parentid' , isLogin , function(요청,응답){
res.writeHead(200, {
"Connection": "keep-alive",
"Content-Type": "text/event-stream",
"Cache-Control":"no-cache",
});
console.log(ObjectId(요청.params.parentid));
db.collection('message').find({ parent : ObjectId(요청.params.parentid) }).toArray()
.then((결과)=>{
res.write('event: test\n');
// res.write('data :' + result +'\n\n');
res.write('data : ' + JSON.stringify(결과) +'\n\n');
// })});
-------------------------
chat.ejs
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
<script>var currentRoomId;
var eventSource;
$('.list-group-item').click(function(){ //여기를클릭하면
alert('대화방 선택이 되었음');
currentRoomId = this.dataset.id;if(eventSource!=undefined){
eventSource.close()
}
//여기채널입장.
eventSource = new EventSource('/message/' + currentRoomId);
eventSource.addEventListener('test',function(e){
console.log(JSON.parse(e.data)); //서버가 데이터 보내주면 출력
var takeFrom = JSON.parse(e.data);
takeFrom.forEach(function(i){
$('.chat-content').append('<li><span class="chat-box">'+i.content+'</span></li>');
})
});
});$('#send').click(function(){
//채팅 메세지 게시물에는 어떤정보들이 저장되어야할까? (발행자id, 모글_id, 내용,날짜)
var chatMainText =$('#chat-input').val();
alert(chatMainText);
var send_data ={
//채팅방클릭하면 채워지게
parent: currentRoomId,
content : chatMainText
}
$.post('/message',send_data).then(()=>{
console.log('전송성공');
})
});2022년 4월 4일 10:06 #31050
codingapple키 마스터ejs파일에서 currentRoomId = this.dataset.id;
여부터 currentRoomId가 잘 출력되는지 확인해봅시다
2022년 4월 4일 12:55 #31070
Eric참가자출력은 잘되고 있씁니다.
alert("제이슨" + JSON.parse(e.data)); 내용에서 e.data내용이 안뜨는것 같은데 db에서 불러오는 부분에서 문제가 있을까요?
app.get('/message/:id' , isLogin , function(요청,응답){
응답.writeHead(200, {
"Connection": "keep-alive",
"Content-Type": "text/event-stream",
"Cache-Control":"no-cache",
});
console.log("채팅방아이디 " + 요청.params.id);
db.collection('message').find({parent:요청.params.id}).toArray()
.then((결과)=>{
응답.write('event: test\n');
// res.write('data :' + result +'\n\n');
응답.write('data : ' + JSON.stringify(결과) +'\n\n');});
2022년 4월 4일 20:01 #31110
codingapple키 마스터서버에서 JSON.stringify(결과) 이거 출력해보면 잘 뜨고 있나요 안뜨면 db에서 데이터가져오는 문법이 잘못된 걸 수 있습니다
2022년 4월 5일 09:32 #31149
codingapple키 마스터그러면 .find({parent:요청.params.id}) 이걸로 찾은 결과가 아무것도 없거나 그런경우같은데
요청.params.id가 잘 출력되는지 프론트엔드에서도 잘 보내고 있는지 이런식으로 차례로 확인해나가면 됩니다
-
글쓴이글
- 답변은 로그인 후 가능합니다.