node.js교과서 개정 2판 학습중
9.5.1 스스로 해보기
팔로잉 끊기 기능
메인의 게시글 목록에서도 팔로우 끊기를 할 수 있고, 내 프로필의 팔로잉 목록에서도 팔로우 끊기를 할 수 있도록했다.
우선 main.html의 프론트 부분 수정
//main.html
...
{% if not followerIdList.includes(twit.User.id) and twit.User.id !== user.id %}
<button class="twit-follow abled">팔로우하기</button>
{% elif followerIdList.includes(twit.User.id) and twit.User.id !== user.id%}
<button class="twit-unfollow ">팔로우끊기</button>
{% endif %}
...
<script>
...
document.querySelectorAll('.twit-unfollow').forEach(function(tag) {
tag.addEventListener('click', function() {
const myId = document.querySelector('#my-id');
if (myId) {
const userId = tag.parentNode.querySelector('.twit-user-id').value;
//console.log(`userId:${userId}`);
if (userId !== myId.value) {
if (confirm('팔로잉을 끊겠습니까?')) {
axios.post(`/user/${userId}/unfollow`)
.then(() => {
location.reload();
})
.catch((err) => {
console.error(err);
});
}
}
}
});
});
내 프로필의 팔로잉 목록에서도 팔로우를 끊을 수 있게 profile.html에서 프론트를 수정한다.
//profile.html
...
<h2>팔로잉 목록</h2>
{% if user.Followings %}
{% for following in user.Followings %}
<div>
<input id="following-id" type="hidden" value="{{following.id}}"/>
<div class ="following-nic">{{following.nick}}</div>
<button class="twit-follow-cancle">팔로우 끊기</button>
</div>
{% endfor %}
{% endif %}
</div>
...
<script>
document.querySelectorAll('.twit-follow-cancle').forEach(function(tag){
tag.addEventListener('click',function(){
const myId = document.querySelector('#my-id');
if(myId){
const userId=tag.parentNode.querySelector('#following-id').value;
if (userId !== myId.value) {
if (confirm('팔로잉을 끊겠습니까?')) {
axios.post(`/user/${userId}/unfollow`)
.then(() => {
location.reload();
})
.catch((err) => {
console.error(err);
});
}
}
}
});
});
</script>
{% endblock %}
/routers/user.js 파일에서 언팔로우에 대한 라우터를 생성한다.
// routes/user.js
...
router.post('/:id/unfollow',isLoggedIn,async(req,res,next)=>{
try{
const user = await User.findOne({ where: {id : req.user.id }});
if(user){
await user.removeFollowing(parseInt(req.params.id,10));
res.send('success');
}else{
res.status(404).send('no user');
}
}catch(error){
console.error(error);
next(error);
}
});
...
메인,프로필에서의 언팔 요청이 다 이 라우터로 받아진다.