6 글 보임 - 1 에서 6 까지 (총 6 중에서)
-
글쓴이글
-
2023년 5월 3일 07:13 #80584
강호문참가자안녕하세요? 문제 해결해주느라 수고하시는데 대해 항상 감사하게 생각하고 있습니다~~ 제 코딩이 아래와 같습니다만 2가지 질문이 있습니다. 1. /chat에서 화면 상에는 chatter, chatted 다 나오는데 db에 parent가 null로 나오는 문제 2. 채팅 버튼이 눌렀을 때 확인 하려고 console.log('채팅방 게시물 생성완료') 삽입했으나 반응이 없는 것. 1. list.ejs
<!doctype html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link href="/public/main.css" rel="stylesheet">
<title>Hello, world!</title> </head> <body> <%- include('nav.html') %> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<h4 class="ml-2 my-3 text-center">서버에서 가져온 할일 리스트</h4> <div class="container"> <ul class="list-group"> <% for (var i = 0; i < posts.length; i ++) { %> <li class="list-group-item"> <p>글번호: <%= posts[i]._id %></p> <h5>제목:<%= posts[i].제목 %></h5> <p>일자: <%= posts[i].날짜 %></p> <button class="btn btn-danger delete" data-id = "<%= posts[i]._id %>">삭제</button> <button class="btn btn-secondary chat" data-id = "<%= posts[i].작성자 %>">채팅</button> <% } %> </div>
<script> $('.chat').click(function(e){ console.log(dataset) console.log(data-id) var id = e.target.dataset.id; $.post('/chatroom', {당한사람id : id}).then(()=>{ console.log('채팅방 게시물 생성완료') }) }); </script>
<script> $('.delete').click(function(e){ var 글번호 = e.target.dataset.id; var 지금누른거=$(this); $.ajax({ method : 'DELETE', url : '/delete', data : {_id :글번호 } }).done(function(결과){ console.log('성공했어요') 지금누른거.parent('li').fadeOut();
}).fail(function(xhr,textStatus,errorThrown){ console.log(xhr,textStatus,errorThrown) }) }) </script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> </body> </html>
2. server.js
const express = require('express') const app = express() const{ObjectId} = require('mongodb');
app.use(express.urlencoded({ extended: true }));
const MongoClient = require('mongodb').MongoClient const methodOverride = require('method-override') app.use(methodOverride('_method')) app.set('view engine', 'ejs'); app.use('/public', express.static('public'))
var db;
MongoClient.connect('mongodb+srv://admin:tORiZJNFRHzEWvEG@cluster0.arwhvq8.mongodb.net/?retryWrites=true&w=majority', function(에러,client){ if(에러) return console.log(에러) db=client.db('todoapp');
app.listen(8080, function(){console.log('listening on 8080') }); }); app.get('/', function(요청, 응답) { 응답.render('login.ejs')// 응답.sendFile(__dirname +'/index.html') // 응답.render('index.ejs') })
app.get('/write', function(요청, 응답) { // 응답.sendFile(__dirname +'/write.html') 응답.render('write.ejs') });
app.get('/list', function(요청,응답 ){ db.collection('post').find().toArray(function(에러, 결과){console.log(결과) 응답.render('list.ejs', {posts: 결과}) } ) })
app.get('/detail/:id', function(요청,응답 ){ db.collection('post').findOne({_id: parseInt(요청.params.id)}, function(에러,결과){ console.log(결과);
응답.render('detail.ejs', {data : 결과}) }) })
app.get('/edit/:id', function(요청, 응답){ db.collection('post').findOne({ _id : parseInt(요청.params.id) }, function(에러, 결과){ console.log(결과) 응답.render('edit.ejs', { post : 결과 }) }) });
app.put('/edit', function(요청, 응답){ db.collection('post').updateOne( {_id : parseInt(요청.body.id) }, {$set : { 제목 : 요청.body.title , 날짜 : 요청.body.date }}, function(에러, 결과){ console.log('수정완료') 응답.redirect('/list') }); });
const passport = require('passport'); const LocalStrategy = require('passport-local').Strategy; const session = require('express-session'); //app.use는 미들웨어. 요청-응답 중간에 뭔가 실행되는 코드 app.use(session({secret : '비밀번호', resave : true, saveUninitialized: false})); app.use(passport.initialize()); app.use(passport.session());
app.get('/login', function(요청,응답){응답.render('login.ejs') } );;
app.post('/login', passport.authenticate('local', {failureRedirect : '/fail'}), function(요청, 응답){ 응답.redirect('/list')});
app.get('/mypage', 로그인했니, function (요청, 응답) { console.log(요청.user); 응답.render('mypage.ejs', { 사용자: 요청.user }) }) function 로그인했니(요청, 응답, next) { if (요청.user) { next() } else { 응답.send('로그인안하셨는데요?') } }
passport.use(new LocalStrategy({ usernameField: 'id', passwordField: 'pw', session: true, passReqToCallback: false, }, function (입력한아이디, 입력한비번, done) { console.log(입력한아이디, 입력한비번); db.collection('login').findOne({ id: 입력한아이디 }, function (에러, 결과) { if (에러) return done(에러)
if (!결과) return done(null, false, { message: '존재하지않는 아이디요' }) if (입력한비번 == 결과.pw) { return done(null, 결과) } else { return done(null, false, { message: '비번틀렸어요' }) } }) }));
passport.serializeUser(function (user, done) { done(null, user.id) });
passport.deserializeUser(function (아이디, done) { db.collection('login').findOne({ id: 아이디 }, function (에러, 결과) { done(null, 결과) }) });
app.post('/register', function(요청, 응답){ db.collection('login').insertOne({id: 요청.body.id, pw:요청.body.pw }, function(에러,결과){ 응답.redirect('/') }) })
app.post('/add', function (요청, 응답) { db.collection('counter').findOne({name : '게시물갯수'}, function(에러, 결과){ var 총게시물갯수 = 결과.totalPost var 저장할거 = {_id : 총게시물갯수 + 1, 제목 : 요청.body.title, 날짜 : 요청.body.date, 작성자: 요청.user._id} db.collection('post').insertOne( 저장할거, function (에러, 결과) {
db.collection('counter').updateOne({name:'게시물갯수'},{ $inc: {totalPost:1} },function(에러, 결과){ if(에러){return console.log(에러)} 응답.redirect('/list'); }) }) }) })
app.delete('/delete',function(요청,응답){ console.log(요청.body) 요청.body._id = parseInt(요청.body._id );
var 삭제할데이터={_id : 요청.body._id, 작성자 : 요청.user._id} db.collection('post').deleteOne(삭제할데이터, function(에러, 결과){ console.log('삭제 완료'); if(에러){console.log(에러)} if(결과){console.log(결과)} 응답.status(200).send({message:'Send sucessful'}) }) })
// app.get('/search', (요청, 응답)=>{ // console.log(요청.query); // db.collection('post').find({제목 : 요청.query.value}).toArray((에러, 결과)=>{ // console.log(결과) // 응답.render('search.ejs', {posts:결과}) // }) // })
app.get('/search', (요청, 응답)=>{
var 검색조건 = [ { $search: { index: 'hmindex', text: { query: 요청.query.value, path: '제목' // 제목날짜 둘다 찾고 싶으면 ['제목', '날짜'] } } } ] console.log(요청.query); db.collection('post').aggregate(검색조건).toArray((에러, 결과)=>{ console.log(결과) 응답.render('search.ejs', {posts : 결과}) }) })
app.post('/chatroom', 로그인했니, function(요청, 응답){ var 저장할거={ title :'채팅방', member : [ObjectId(요청.body.당한사람id), 요청.user._id], date : new Date() } db.collection('chatroom').insertOne(저장할거).then((결과)=>{ 응답.send('send로응답성공') }) });
app.get('/chat', 로그인했니, function(요청, 응답){
db.collection('chatroom').find({ member : 요청.user._id }).toArray().then((결과)=>{ console.log(결과); 응답.render('chat.ejs', {data : 결과}) }) });
app.post('/message', 로그인했니, function(요청, 응답){ console.log(요청.body) var 저장할거 = { parent : 요청.body.parent, userid : 요청.user._id, content : 요청.body.content, date : new Date(), } db.collection('message').insertOne(저장할거) .then((결과)=>{ console.log(저장할거) 응답.send(결과); }) });
app.get('/message/:parentid', 로그인했니, function(요청, 응답){
응답.writeHead(200, { "Connection": "keep-alive", "Content-Type": "text/event-stream", "Cache-Control": "no-cache", }); db.collection('message').find({ parent: 요청.params.parentid }).toArray() .then((결과)=>{ console.log(결과); 응답.write('event: test\n'); 응답.write(`data: ${JSON.stringify(결과)}\n\n`); }); const 찾을문서 = [ { $match: { 'fullDocument.parent': 요청.params.parentid } } ]; const changeStream = db.collection('message').watch(찾을문서); changeStream.on('change', result => { console.log(result.fullDocument); var 추가된문서 = [result.fullDocument]; 응답.write(`data: ${JSON.stringify(추가된문서)}\n\n`); }); }); 3. chat.ejs
<!doctype html> <html > <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <link rel="stylesheet" href="/public/main.css">
<div class="container p-4 detail">
<div class="row"> <div class="col-3"> <ul class="list-group-item chat-list"> <% for (var i=0; i < data.length ; i++){ %> <li class="list-group-item" data-id="<%= data[i]._id %>"> <h6> <%= data[i].title %> <%= data[i]._id %></h6> <h6 class="text-small"> chatted<%= data[i].member[0] %> </h6> <h6 class="text-small"> chatter<%= data[i].member[1] %> </h6> <% } %>
</div> <div class="col-9 p-0"> <div class="chat-room"> <ul class="list-group chat-content">
- <span class="chat-box">채팅방1 내용</span>
- <span class="chat-box">채팅방1 내용</span>
- <span class="chat-box mine">채팅방1 내용</span>
<div class="input-group"> <input class="form-control" id="chat-input"> <button class="btn btn-secondary" id="send">전송</button> </div> </div> </div><script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <script> var 지금누른채팅방id; var eventSource; $('.list-group-item').click(function(){ 지금누른채팅방id = this.dataset.id; console.log('채팅 버튼 눌렀어요')
eventSource = new EventSource('/message/' ); eventSource.addEventListener('test', function (e){ console.log(e.data);
}) })
$('#send').click(function(){ var 채팅내용 = $('#chat-input').val(); var 보낼거 = { parent: 지금누른채팅방id, content: 채팅내용, }; $.post('/message', 보낼거).then(() => { console.log(전송성공) }); }); </script>
</html>
2023년 5월 3일 09:39 #80604
codingapple키 마스터채팅방누르면 지금누른채팅방id 변수부터 잘 나오나 출력해봅시다 2는 post요청시 서버기능 잘 실행되는지 console.log 같은거 써봅시다
2023년 5월 3일 15:42 #80703
강호문참가자채팅 버튼 누르면 아래와 같이 dataset is not defined 로 나오는데요~~
jQuery-3.2.1.min.js:2 jQuery.Deferred exception: dataset is not defined ReferenceError: dataset is not defined at Object.<anonymous> (http://localhost:8080/list:106:19) at j (https://code.jquery.com/jquery-3.2.1.min.js:2:29999) at k (https://code.jquery.com/jquery-3.2.1.min.js:2:30313) undefined r
-
글쓴이글
6 글 보임 - 1 에서 6 까지 (총 6 중에서)
- 답변은 로그인 후 가능합니다.