관리자 페이지, 로그인, 로그아웃, 메인화면, 회원가입

keep_going·2022년 12월 15일
0

js

목록 보기
4/9

관리자 페이지
itemseller.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>판매자 물품관리</title>
    <style>
    .container {
        margin  : 2px;
        border  : 3px solid #cccccc;
    }

    header {
        background-color: rgb(255, 247, 176);
        text-align      : center;
        padding         : 20px;
        color           : rgb(195, 0, 255);
    }
    
    footer {
        background-color: rgb(195, 0, 255);
        text-align      : center;
        padding         : 20px;
        color           : rgb(255, 247, 176);
    }
    /* 쪼갤게 아니기 때문에 사실 없어도됨. */
    section {
        background-color: rgb(255, 253, 240);
    }

    table {
        width          : 100%;
        border-collapse: collapse;
        padding: 10px;
    }
    </style>
</head>

<body>
    <div class="container">
        <header>
            <h3>header 영역</h3>
        </header>

        <section>
            <table border="1">
                <thead>
                    <tr>
                        <th>물품번호</th>
                        <th>물품사진</th>
                        <th>물품명</th>
                        <th>물품설명</th>
                        <th>가격</th>
                        <th>수량</th>
                        <th>등록날짜</th>
                        <th width="100px">버튼</th>
                    </tr>
                </thead>
                <tbody id="tbody"></tbody>
            </table>
        </section>

        <footer>
            <h3>footer 영역</h3>
        </footer>
    </div>

    <script src="js/axios.min.js" type="text/javascript"></script>
    <script> 

        //공통영역, 자동실행
        const tbody = document.getElementById('tbody');
        console.log(tbody);

        //함수는 자동호출 안됨 -> 그래서 위치 상관없음!

        const handleUpdate = async(no, idx) => { // 호출한 곳에서 번호와 위치가 필요 
            // 번호는 input으로 받은게 아니라서 위치와 달리 수정시 이용할 수 없다. url에 필요한것. 위치는 최근 게시물 부터 0,1,2..
            // 태그 연결하기
            // class로 설정했으므로 [<input><input>...<input>] -> 전체중에 수정을 원하는 한줄만 필요함!
            // 함수가 붙을때만 필요해서 함수안에 넣음
            const name      = document.getElementsByClassName('name');
            const content   = document.getElementsByClassName('content');
            const price     = document.getElementsByClassName('price');
            const quantity  = document.getElementsByClassName('quantity');
            if(confirm('수정할까요?')) {
                const url =`http://1.234.5.158:23000/item101/update.json?no=${no}`; // 번호 필요
                const headers = {"Content-Type":"application/json"}
                const body = {
                    name : name[idx].value, // 수정하려고 하는 상품의 위치가 필요. 아니면 다른 물품까지 수정되버리잖아! 이걸 여기서 받아서 함수의 ()에 넣어줘야함.
                    content : content[idx].value,
                    price : price[idx].value, 
                    quantity : quantity[idx].value
                }
                const { data } = await axios.put(url, body, {headers});
                console.log(data);
                if (data.status === 200) {
                    window.location.href="/itemseller1.html";
                }
            }
        }

        const handleDelete = async(no) => { // 밑에서 onclick 뒤에 받은 ${data.result[i]._id} 정보를 no로 받은것
            console.log(no);
            if(confirm('삭제할까요?')) { // const result=confirm('삭제할까요?') 하고 if(result === true)를 한줄로 표현한것
                const url = `http://1.234.5.158:23000/item101/delete.json?no=${no}`; 
                // 게시글 삭제는 item이 아니라 board였음.. 활용할 생각 말고 올라와있는것 쓰기
                const headers = {"Content-Type":"application/json"};
                const body = {}
                const { data } = await axios.delete(url, {headers:headers, data:body});  
                console.log('handleDelete', data);
                if(data.status === 200) {
                    window.location.href="itemseller1.html";  
                }
            }
        }

        //function handleData()
        //const handleData = async() => {} 
        //위 두줄 같은것 
        const handleData = async() => { 
            const url = `http://1.234.5.158:23000/item101/selectlist.json`;
            const headers = {"Content-type":"application/json"};
            // 객체 {key:value}
            // {headers:headers} == {a:a} 이게 원래 모양, headers도 원래 object
            const { data } = await axios.get(url, {headers});
            console.log('handleData', data);
            //원래는 const response
            //console.log(response.data)
            //모든 프레임 워크는 이런 형식으로 같음... const {data} 라인이 백엔드 호출 후 기다렸다가 다시 받는거 까지 하는거임.

            if(data.status === 200) {
                console.log(data.result) // 필요한 값 result이므로 확인 먼저!, 배열인지 아닌지도 모르잖어. 형태 확인도 해야한다.
            
                // forEach
                // ex) [{0},{1}...{20}] => 길이는 21
                // for(let tmp of data.result) { <<숫자가 필요 없을때
                //     console.log(tmp)
                // }

                // for
                // const arr=[34,556,223] => arr[0], arr[1], arr[2]
                for(let i=0; i<data.result.length; i++) { // 처음부터 거짓이면 한번도 안돌아감. tmp에 복사되고 있는게 아니라 숫자만 증가하는중.
                    console.log(i, data.result[i]); //숫자를 알수 있기 때문에 좋음. 몇번째꺼의 데이터를 찍어라가 가능해짐. 찍는 위치를 알수 있다.
                    tbody.innerHTML +=
                     `<tr>` +
                        `<td>${data.result[i]._id}</td>` + // data.result[i]가 원래 사용하던 tmp인것
                        `<td><img src="${data.result[i].img}" style="height: 80px" /></td>` +
                        `<td><input type="text" class="name" value="${data.result[i].name}" /></td>` +
                        // 물품명.. 등 여러개를 받아야 하므로 class로 받으므
                        `<td><textarea rows="4" class="content" width="100%">${data.result[i].content}</textarea></td>` +
                        `<td><input type="number" class="price" value="${data.result[i].price}" style="width:150px" /></td>` + 
                        `<td><input type="number" class="quantity" value="${data.result[i].quantity}" style="width:50px" /></td>` +
                        `<td>${data.result[i].regdate}</td>` +
                        `<td>` +
                            `<buttontoken interpolation">${data.result[i]._id}, ${i})">수정</button>` + 
                            // 수정 화면 따로 만들면 불편. 이 화면에서 바로 수정하고 수정 버튼 누르면 수정되도록 만들고 싶다.
                            // 번호와 위치를 동시에 받음
                            `<buttontoken interpolation">${data.result[i]._id})">삭제</button>` + 
                            // 버튼 누를때 어떤 정보를 받아야하는지 알려줘야한다. 번호가 필요하다. 함수를 호출하는 곳에서 정보를 전달해줘야한다.
                            `</td>` ;
                     `</tr>` ;
            }
        }
    }
    handleData();
    </script>
</body>
</html>

회원가입
join1.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>회원가입</title>
    <style>
        .container {
            width: 800px;
            border: 1px solid #cccccc;
            margin: 0 auto;
            padding: 20px;
            background-color: rgb(254, 255, 219);
        }
        .item {
            margin: 10px;
        }
        .lbl {
            display : inline-block;
            width   : 100px;
            margin  : 10px;
        }
    </style>
</head>

<body>
    <div class="container">
        <h3>회원가입</h3>
        <hr />

        <div class="item">
            <label class="lbl">아이디</label>
            <input type="text" onkeyup="handleIDCheck()" id="id" placeholder="아이디를 입력하세요." autofocus/>
            <!-- 실시간으로 아이디 중복 확인. 키를 눌렀다가 뗄때! -->
            <label class="lbl" id="check">중복확인</label>
            
        </div>
   
        <div class="item">
            <label class="lbl">암호</label>
            <input type="password" id="pw" placeholder="비밀번호를 입력하세요." />
        </div>
  
        <div class="item">
            <label class="lbl">암호 확인</label>
            <input type="password" id="pw1" placeholder="비밀번호를 다시 입력하세요." />
        </div>
  
        <div class="item">
            <label class="lbl">이름</label>
            <input type="text" id="name" placeholder="이름을 입력하세요." />
        </div>
 
        <div class="item">
            <label class="lbl">이메일</label>
            <input type="text" id="email"placeholder="이메일을 입력하세요." />
            <label>@</label>
            <select id="email1" >
                <option>이메일 주소 선택</option>
                <option>naver.com</option>
                <option>google.com</option>
                <option>daum.net</option>
            </select>
        </div>
 
        <div class="item">
            <label class="lbl">나이</label>
            <input type="number" id="age" placeholder="나이를 입력하세요." value="0"/>
        </div>

        <hr />

        <div class="item">
            <label class="lbl"></label>
            <button onclick="handleJoin()">회원가입</button>
            <a href="/main1.html"><button>홈으로</button></a>
        </div>
    </div>

    <script src="js/axios.min.js" type="text/javascript"></script>
    <script>
        const id = document.getElementById('id');
        const check = document.getElementById('check');
        const pw = document.getElementById('pw');
        const pw1 = document.getElementById('pw1');
        const name = document.getElementById('name');
        // id로 설정한 것들은 고유하므로 따로 상수로 선언하지 않아도 인식된다.
        // 그런데 왜 name은 오류가 뜰까? name은 상수 선언안하니 오류뜸..

        // 전역변수, 함수 어디에서나 사용가능함.
        let idcheck = 0;

        const handleIDCheck = async() => {
            if(id.value.length > 0) { 
                const url = `http://1.234.5.158:23000/member101/idcheck.json?id=${id.value}`;
                const headers ={"Content-Type":"application/json"};
                const { data } = await axios.get(url, {headers});
                console.log('handleIDCheck', data);
                if(data.status === 200){
                    if(data.result === 0) {
                        check.innerHTML 
                            = '<label style="color:green;">사용가능</label>';
                            idcheck = 1;
                    }
                    else if(data.result === 1) {
                        check.innerHTML 
                            = '<label style="color:red;">사용불가</label>';
                            idcheck = 0;
                    }
                }
            }
            else {
                check.innerHTML = '중복확인';
                idcheck = 0;
            }
        }

        const handleJoin = async() => {
            if (id.value.length <=0) { 
                alert('아이디를 입력하세요.');
                id.focus();
                return false; // 함수종료
            }
            // 전역변수를 이용하여 아이디 중복 유무 확인하기
            if(idcheck === 0) {
                alert('아이디 중복 확인하세요.');
                id.focus();
                return false;
            }
            if (pw.value.length <=0) {
                alert('비밀번호를 입력하세요.');
                pw.focus();
                return false;
            } 
            if (pw1.value.length <=0) {
                alert('비밀번호를 다시 입력하세요.');
                pw1.focus();
                return false;
            } 
            // === 같다 !== 같지않다
            if (pw.value !== pw1.value) {
                alert('암호가 일치하지 않습니다.');
                pw1.focus();
                return false;
            }
            // 왜 여기서 안넘어가는거지? name을 위에서 상수로 선언하고 나니까 넘어감... 어딘가에서 name이 또 사용된건가?
            if (name.value.length <=0 ) {
                alert('이름을 입력하세요.');
                name.focus();
                return false;
            }
            if (email.value.length <=0) {
                alert('이메일을 입력하세요.');
                email.focus();
                return false;
            }
            if (email1.value === '이메일 주소 선택') {
                alert('이메일 주소를 선택하세요.');
                email.focus();
                return false;
            }
            if (age.value <= 0) {
                alert('나이를 입력하세요.');
                return false;
            }
            
            // 유효성 검사 통과, 백엔드 연동할 위치
            const url = `http://1.234.5.158:23000/member101/insert.json` ;
            const headers = {"Content-Type":"application/json"} ;
            const body = {
                id: id.value,
                pw: pw.value,
                name: name.value,
                email: email.value + "@" + email1.value, 
                age: age.value
            }  
            const { data } = await axios.post(url, body, {headers});
            console.log(data);
            if(data.status === 200) {
                alert('회원 가입 성공!')
                window.location.href="/main1.html";
            }
        }
    </script>
</body>

</html>

로그인
login1.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>로그인</title>
    <style>
        .container {
            width           : 900px;
            margin          : 0px auto;
            border          : 1px solid #cccccc;
            background-color: #fafafa;
        }
        header {
            background-color : rgb(254, 255, 209);
            text-align       : center;
            padding          : 30px;
            color            : rgb(255, 208, 0);
        }
        footer {
            background-color : rgb(255, 239, 209);
            text-align       : center;
            padding          : 30px;
            color            : #ca7900d7;
        }
        .item{
            margin  : 10px;
            padding : 10px;
        }
        .lbl{
            display : inline-block;
            width  : 100px;
        }
    </style>
</head>

<body>
    <div class="container">
        <header>header</header>

        <div class="item">
            <label class="lbl">아이디</label>
            <input type="text" id="id" placeholder="아이디를 입력하세요." autofocus/>
        </div>

        <div class="item">
            <label class="lbl">암호</label>
            <input type="password" id="pw" placeholder="비밀번호를 입력하세요." />
        </div>

        <div class="item">
            <hr />
            <label class="lbl"></label>
            <button onclick="handleLogin()">로그인</button>
            <a href="/main1.html"><button>홈으로</button></a>
        </div>

        <footer>footer</footer>

        <script src="js/axios.min.js" type="text/javascript"></script>
        <script>
            const id = document.getElementById('id') ;
            const pw = document.getElementById('pw') ;

            const handleLogin = async() => {
                if(id.value.length <=0 ) {
                    alert('아이디를 입력하세요.')
                    id.focus();
                    return false;
                }
                if(pw.value.length <=0 ) {
                    alert('비밀번호를 입력하세요.')
                    pw.focus();
                    return false;
                }
                
                const url = `http://1.234.5.158:23000/member101/select.json`;
                const headers = {"Content-Type":"application/json"} ;
                const body = {
                    id : id.value,
                    pw : pw.value
                }
                const { data } = await axios.post(url, body, {headers});
                console.log(data);
                if(data.status === 200) {
                    alert('로그인 되었습니다.')
                    
                    // main, join, login 이런 파일들은 서로 무슨일이 일어났는지 모른다.
                    // 로그인에 성공했다면 그 상황을 나머지 파일들도 알아야 거기에 알맞는 화면을 내보낼 수 있다.
                    // 창이 떠있는 동안 공통적으로 접근할수 있는게 필요-> 그게 storage. 저장소.
                    // 크롬에서 f12 => >> => applicaion => storage
                    // 세션스토리지에 로그인 했던 기록을 저장. 로그인 전후 화면이 달라지기 위해서는 기록이 저장되어야 함.
                     // ex) 키는 TOKEN. 내마음대로
                    sessionStorage.setItem("TOKEN", data.result);
                    // 토큰이 result 값
                    // 토큰은 시간이 정해져있음. 정해진 시간이 지나면 활용 할수 없다.

                    // 로그인하고 토큰을 저장소에 보내놓으면 메인이 저장소에서 토큰을 가져와서 로그인 했는지 확인!
                    // sessionStorage.getItem()

                    // 세션스토리지의 내용 지우기(로그아웃에서 해야함)
                    // sessionStorage.removeItem("TOKEN");
                    
                    window.location.href="/main1.html";
                }
                else{
                    alert('아이디 또는 비밀번호를 확인하세요.')
                }
            }
        </script>
    </div>
</body>

</html>

로그아웃
logout1.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>로그아웃</title>
</head>
<body>
    
    <script>
        if(confirm('로그아웃할까요?')) {
            // 세션 스토리지에 토큰정보 지우기
            sessionStorage.removeItem('TOKEN');
        }
        // 다시 메인화면으로 이동하기
        window.location.href="/main1.html"
    </script>
</body>
</html>

메인화면
main1.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>메인화면</title>
    <style>
        .container {
            width: 900px;
            margin  : 0px auto;
            border  : 1px solid #cccccc;
            background-color: #fafafa;
        }
        header{
            background-color : rgb(254, 255, 209);
            text-align       : center;
            padding          : 30px;
            color            : rgb(255, 208, 0);
        }
        footer{
            background-color : rgb(255, 239, 209);
            text-align       : center;
            padding          : 30px;
            color            : #ca7900d7;
        }
        section{
            display: grid;
            grid-template-columns: 200px auto 100px;
        }
        nav{
            padding : 20px;
            border : 1px solid #cccccc ;
        }
        article{
            border : 1px solid #cccccc ;
        }
        side{
            border : 1px solid #cccccc ;
        }
    </style>
</head>

<body>
    <div class="container">
        <header>
            header 
        </header>

        <section>
            <nav>
                <div>
                    <a href="/board1.html">게시판목록</a>
                </div>    
                <div id="menu1">
                    <h3>로그인 전의 메뉴</h3>
                    <a href="/join1.html">회원가입</a>
                    <a href="/login1.html">로그인</a>
                </div>
                <div id="menu2">
                    <h3>로그인 후의 메뉴</h3>
                    <a href="/logout1.html">로그아웃</a>
                </div>        
            </nav>
            <article>

            </article>
            <side>

            </side>
        </section>

        <footer>
            footer 
        </footer>

       
    </div>
    <script>
        const menu1 = document.getElementById('menu1');
        const menu2 = document.getElementById('menu2');
       
        // 세션스토리지에서 내용가져오기
        // 토큰(사용자인증)이 있으면 토큰정보가 표시, 없으면 null
        const token = sessionStorage.getItem('TOKEN');
        console.log(token);

        if(token === null) { // 로그인 되지 않음
            menu1.style.display = "block";
            menu2.style.display = "none";
        }
        else { // 로그인 되었음
            menu1.style.display = "none";
            menu2.style.display = "block";
        }
    </script>
</body>

</html>
profile
keep going

0개의 댓글