login.ejs 2.28 KB
<!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>Mukho - login form</title>
</head>
<body>
    <form action="/register/form" method="post">
        <h2>Hello. It's me mukho.</h2>

        <a href="http://localhost:3000/main">main</a>
        <a href="http://localhost:3000/about">about</a>
        <a href="http://localhost:3000/info">info</a><br/>

        id : <input type="text" name="ID" required minlength='1' maxlength='20'><br/>
        password : <input type="password" name="password" required minlength='1' maxlength='20'><br/> <!-- type password는 입력 값을 *로 표시함-->
    </form>

    <button class="ajaxsend">Login</button>
    <div class="result"></div>

    <script>
        document.querySelector('.ajaxsend').addEventListener('click', function(){
            var ID = document.getElementsByName('ID')[0].value;
            var password = document.getElementsByName('password')[0].value;
            sendAjax('http://localhost:3000/login', {'ID' : ID, 'password' : password});
        })

        function sendAjax(url, data){
            data = JSON.stringify(data);
            var xhr = new XMLHttpRequest();
            xhr.open('POST', url);
            xhr.setRequestHeader('Content-Type', "application/json"); // 서버로 보낼 때 json type으로 보내겠다.
            xhr.send(data);

            xhr.addEventListener('load', function(){
                var result = JSON.parse(xhr.responseText);
                var resultDiv = document.querySelector(".result");
                // 웹 반응
                if(result.ID){
                    //resultDiv.innerHTML = "반갑다 "+result.ID;
                    window.location.href="/main"; // main으로 가라
                }
                else if(xhr.status === 401) resultDiv.innerHTML = result + "<div class='signup'><a href='/join'>Sign up</a></div>";
                else resultDiv.innerHTML = result;
                // if(!result.ID) resultDiv.innerHTML = result;
                // else if(result.password != password) resultDiv.innerHTML = result;
                // else resultDiv.innerHTML = result.ID;
            });
        };
    </script>
</body>
</html>