4 글 보임 - 1 에서 4 까지 (총 4 중에서)
-
글쓴이글
-
2023년 1월 17일 17:32 #63127
최다안참가자채팅방 생성 버튼을 누르면, ajax로 post 요청하도록 했는데 로그인했니라는 미들웨어 함수가 동작하지 않습니다... ejs 파일에서 ajax 요청 $('.chat').click(function(e){ var 글번호 = e.target.dataset.id; $.post('/chatroom', {_id : 글번호}) .then(()=>{ console.log('채팅방 게시물 생성완료') }) }); server.js 파일 app.post('/chatroom', 로그인검사, function(요청, 응답) { console.log(요청.body); console.log(요청.user); }); });
function 로그인검사(요청, 응답, next) { if (요청.user) { next() } else { 응답.send( `<script> alert('로그인안하심'); location.href='/login'; </script>` ); } }
로그인했니 미들웨어가 동작하지 않는 라우터를 보니 공통적으로 ejs파일에서 ajax방식으로 요청한 것들이였습니다. 구글링해도 못찾겠어서 질문 올립니다.
2023년 1월 17일 19:49 #63144
codingapple키 마스터응답.send는 app.post 안에서 씁시다 서버에서 .send로 메세지만 보내고 ajax.then() 안에서 페이지이동시켜도 됩니다
2023년 1월 17일 23:38 #63175
최다안참가자네 감사합니다 근데
(server.js 파일) app.get('/mypage', 로그인했니, function (요청, 응답){ console.log(요청.user); 응답.render('mypage.ejs', {}) })
function 로그인했니(요청, 응답, next) { if (요청.user) { next() } else { 응답.send('로그인안하셨는데요?') } }
server.js파일은 위와 같고 ejs파일에서 a태그를 이용해서 /mypage로 GET 요청했을 때는 미들웨어 안에 응답.send가 정상적으로 작동했었습니다. 그리고 ajax 요청을 할 때는 미들웨어 안에 응답.send('로그인먼저') 이런식으로 응답.send로 메세지만 보내려고 해도 응답.send가 동작하지 않습니다. ajax 요청을 할 때 미들웨어 안에 있는 응답.send('메세지')가 안되는 이유가 무엇인지 알 수 있을까요? (ejs파일) $('.chat').click(function(e){ var 글번호 = e.target.dataset.id; $.post('/chatroom', {_id : 글번호}) .then(()=>{ console.log('채팅방 게시물 생성완료') }) }); (server.js파일) app.post('/chatroom', 로그인검사, function(요청, 응답) { console.log(요청.body); console.log(요청.user); }); }); function 로그인검사(요청, 응답, next) { if (요청.user) { next() } else { console.log(0); 응답.send('로그인 안하심'); } } 여기서 로그인 안한 상태에서 /chatroom으로 post요청을 하면, 콘솔에 0이 찍히는 것은 확인되지만 응답.send('로그인 안하심')은 실행되지 않습니다...
2023년 1월 18일 09:50 #63207
codingapple키 마스터크롬 콘솔창에 console.log('채팅방 게시물 생성완료') 뜨면 응답.send('로그인 안하심') 도 잘 실행되고있는겁니다
-
글쓴이글
4 글 보임 - 1 에서 4 까지 (총 4 중에서)
- 답변은 로그인 후 가능합니다.