본문 바로가기
TIL(Daily)/ETC

Fri/04/Nov/22 Django-시스템추천 프로젝트-3

by Hawie 2022. 11. 7.

오늘은 프로젝트 3일차이다 백엔드 기능 구현은 거의 다 완료 되었고

프론트엔드 를 시작 했다

HTML,CSS 는 해본적 도 있고 찾아  보면 많이 나와있어서 할 수있어 보인다.

문제는 자바스크립트다.

아주 짧은 기초 지식으로 하려다 보니가 너무 막막하다....

 

일단 강의 및 인터넷 구글링을 하면서 찾고 있다.

로그인,회원가입,탈퇴 기능 영화 평점 및 평점 남기기 기능 까지는 구현을 완료 되었다.

 

주말에 팀원들과 함께 다른 못 한 기능 들 과 프론트엔를 어떻게 해야될지 같이 고민해 할 예정이다.

그리고 밑에 코드는 오늘 구현 한기능인다.

 

하지만 솔직히 이해하기는 어렵다.

앞으로 더 공부해서 잘 할수있도록 해야겠다.

 

 

 

#로그인 기능



const frontEndBaseUrl = "http://127.0.0.1:5500"
const backEndBaseUrl = "http://127.0.0.1:8000"
window.onload = () => {
    console.log('로딩되었음')
}

async function handleSignup() {
    const email = document.getElementById("email").value
    const nickname = document.getElementById("nickname").value
    const password1 = document.getElementById("password1").value
    const password2 = document.getElementById("password2").value
    console.log(email, nickname, password1, password2)

    const response = await fetch('http://127.0.0.1:8000/users/dj-rest-auth/registration/', {
        headers: {
            'content-type': 'application/json',
        },
        method: 'POST',
        body: JSON.stringify({
            "email": email,
            "nickname": nickname,
            "password1": password1,
            "password2": password2
        })
    })

    const response_json = await response.json()

    console.log(response)
    if (response.status == 201){
        alert(response_json["detail"])
            window.location.replace(`${frontEndBaseUrl}/login.html`);
    }else {
        alert(response_json["email"])
        alert(response_json["password1"])
        alert(response_json["password2"])

    }
}

async function handleLogin() {
    const email = document.getElementById("email").value
    const password = document.getElementById("password").value
    console.log(email, password)


    const response = await fetch('http://127.0.0.1:8000/users/dj-rest-auth/login/', {
        headers: {
            'content-type': 'application/json',
        },
        method: 'POST',
        body: JSON.stringify({
            "email": email,
            "password": password
        })
    })

    const response_json = await response.json()    // responser 값을 json 화

    console.log(response_json)
    if (response.status == 200){
        localStorage.setItem("access", response_json.access_token);  // 로컬스토리지안에 access값 저장
        localStorage.setItem("refresh", response_json.refresh_token); // 로컬스토리지안에 refresh값 저장

        const base64Url = response_json.access_token.split('.')[1];  // 로컬스토리지에 JWT값 저장
        const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
        const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
        }).join(''));

        localStorage.setItem("payload", jsonPayload);
        alert("로그인 성공!")
            window.location.replace(`${frontEndBaseUrl}/home.html`);

    }else {
        //로그인 실패시
        alert(response_json["non_field_errors"])
        // window.location.reload();
    }
}

async function handleLogout(){
    localStorage.removeItem("access")
    localStorage.removeItem("refresh")
    localStorage.removeItem("payload")
    alert("로그아웃 성공!")
        window.location.replace(`${frontEndBaseUrl}/login.html`);
}

async function handleDelete(){   //mock 함수
    const response = await fetch('http://127.0.0.1:8000/users/delete/',{
        headers:{
            "Authorization":"Bearer " + localStorage.getItem("access")
        },
        method:'DELETE',
    })

    if (response.status ==204){
        alert("회원탈퇴 완료!")
        window.location.replace(`${frontEndBaseUrl}/login.html`);
    }

    console.log(response)
}

async function getMovie(){
    const response = await fetch(`${backEndBaseUrl}/articles/`,{
        method:'GET',
    })

    response_json = await response.json()
    return response_json
}

async function getMovieDetail(movie_id){
    const response = await fetch(`${backEndBaseUrl}/articles/${movie_id}`,{
        method:'GET',
    })
    //window.location.replace(`${frontEndBaseUrl}/articledetail.html/`);
    response_json = await response.json()
    return response_json
}

async function handlePost(movie_id) {
    const content = document.getElementById("content").value
    const rating = document.getElementById("rating").value
    console.log(content, rating)

    const response = await fetch(`http://127.0.0.1:8000/articles/${movie_id}/comment/`, {
        headers: {
            'content-type': 'application/json',
            "Authorization":"Bearer " + localStorage.getItem("access")
        },
        method: 'POST',
        body: JSON.stringify({
            "content": content,
            "rating": rating
        })
    })
    if (response.status ==200){
        window.location.reload();
    }
}

async function MovieCommentDelete(comment) {

    const response = await fetch(`http://127.0.0.1:8000/articles/1/comment/${comment.id}/`, {
        headers: {
            'content-type': 'application/json',
            "Authorization":"Bearer " + localStorage.getItem("access")
        },
        method: 'DELETE',
    })
    if (response.status ==204){
        alert("리뷰가 삭제되었습니다!")
        window.location.reload();
    }
}

댓글