본문 바로가기
  • " 집요함 "
  • " 집요함 "
  • " 집요함 "
웹/백엔드 서버

node.js와 mariaDB로 로그인, 회원가입 만들기

by joen00 2022. 4. 18.

mariaDB와 node.js까지 연결한 상태입니다. 연결 못했으면 npm으로 설치 후 만들면 됩니다. 

 

1. db테이블 만들기

putty에 들어가서 mariadb에 접속한다. 

아래와 같이 입력하여 database와 table을 만들고 내용을 삽입해준다.

sudo mysql -u root -p

CREATE DATABASE member default CHARACTER SET UTF8;
CREATE TABLE user(id int(11),'name' varchar(100) not null, pw varchar(30) not null, primary key(id));
insert into member(name, pw) value(abcd, 1234);

create yser 'abcd'@'localhost' identified by '1234';
grant all privileges on member.*to 'abcd'@'localhost';

 

 

2. maria.js를 만들고 안에 내용은 아래와 같다.

const maria = require("mysql")

const conn = maria.createConnection({ 
    host: 'localhost', 
    user: 'abcd', 
    password: '1234', 
    database:'member' 
});

module.exports=conn;

여기에서 host는 localhost로 나한테서만 보이도록 했다. user와 password는 계정을 설정한 것으로 두고 database는 mariadb에서 만든 것을 이용하였다.

 

2. server.js

const express = require("express")
const app = express() 
const port = 8000 
const maria = require("./maria")

maria.connect();

app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);

app.use(express.json()) 
app.get("/",(req,res)=>{
    res.sendFile(__dirname+"/index.html")
})
app.get("/loginPage",(req,res)=>{
    res.sendFile(__dirname+"/loginPage.html")
})
app.get("/signupPage",(req,res)=>{
    res.sendFile(__dirname+"/signupPage.html")
})

app.post('/signup',(req,res)=>{
    const nameValue = req.body.name 
    const pwValue = req.body.pw
    const sql_value={name:nameValue,pw:pwValue}
    const result = {
        "success" : false
    }
    maria.query('select name from user where name=?',[nameValue],(err,data)=>{
        if(data.length == 0){
            maria.query('insert into user set?',sql_value,(err,data)=>{
                if(err) {
                    throw err;
                }
                else{
                    result.success=true
                    console.log('회원가입 성공');
                    res.send(result)
                }
            });
        }else{
            console.log('회원가입 실패');
            res.send(result)
        }
    });
});

app.post("/login",(req,res)=>{ 
    const name = req.body.name 
    const pw = req.body.pw
    const sql = `SELECT * FROM user WHERE name="${name}"`;
    const result = {
        "success" : false
    }
    maria.query(sql, (err,data)=>{
        if(data.length === 0){
            console.log('로그인 실패');
            res.send(result)
        }
        else if(data[0].pw !== pw){
            console.log('로그인 실패');
            res.send(result)
        }
        else {
            result.success=true;
            console.log(data[0].pw);
            console.log(data[0].name);
            console.log('로그인 성공');
            res.send(result);
        }
    });
})

app.listen(port, ()=>{
    console.log(`${port}번 포트에서 http 통신 시작`)
})


// 확인용
// var params = ['hi', '1234'];//파라미터를 값들로 줌(배열로 생성)
// maria.query('INSERT INTO user (name, pw) VALUES(?, ?)', params, function(err, rows, fields){
//     if(err) console.log(err);
//     console.log(rows.insertId);
// });

// maria.query('SELECT * FROM board', (err, rows, fields)=>{
//     if(err){
//         console.log(err);
//     } 
//     console.log(rows);
// });

// maria.end();

 

3. index.html

<!DOCTYPE html>
<html lang="kr">
<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>Document</title>
</head>
<body>
    <h1>백엔드과정 메인 페이지</h1>
    <input type="button" value="로그인 페이지" onclick="loginPageEvent()">
    <input type="button" value="회원가입 페이지" onclick="signupPageEvent()">
    <script>
        const loginPageEvent=()=>{
            location.href="/loginPage"
        }
        const signupPageEvent=()=>{
            location.href="/signupPage"
        }
    </script>
</body>
</html>

 

4. signupPage.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>
    <h3>회원가입</h3>
    <p>Your name</p>
    <input id ="nameValue" type="text">
    <p>Your password</p>
    <input id ="pwValue" type="text">
    <p></p>
    <input type="button" value="회원가입" onclick="signupEvent()">
    <input type="button" value="메인 페이지" onclick="mainEvent()">
    <script>
         const signupEvent = async () =>{ 
            const result = await fetch("/signup", { 
                "method" : "POST", 
                "headers" : {
                    "Content-Type" : "application/json" 
                },
                "body" : JSON.stringify({
                    "name": document.getElementById("nameValue").value, 
                    "pw": document.getElementById("pwValue").value,
                }) 
            })
            const data = await result.json() 
            if(data.success == true){
                alert("회원가입 성공")
                document.location.href="/loginPage";
            }else{
                alert("회원가입 실패")
            }
        }
        const mainEvent=()=>{
            location.href="/"
        }
    </script>
</body>
</html>

 

5. loginPage.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>
    <h3>로그인</h3>
    <p>Your name</p>
    <input type="text" class="form-input" id ="name">
    <p>Your password</p>
    <input class="form-input" type="text" id ="pw" >
    <p></p>
    <input type="button" value="로그인" onclick="loginEvent()">
    <input type="button" value="메인 페이지" onclick="mainEvent()">
    <script>
        const loginEvent = async () =>{ 
            const result = await fetch("/account/login", { 
                "method" : "POST", 
                "headers" : {
                    "Content-Type" : "application/json" 
                },
                "body" : JSON.stringify({
                    "name": document.getElementById("name").value, 
                    "pw": document.getElementById("pw").value,
                }) 
            })
            const data = await result.json() 
            if(data.success == true){
                alert("로그인 성공")
                document.location.href="/boardlistPage";
            }else{
                alert("로그인 실패")
            }
        }
        const mainEvent=()=>{
            location.href="/"
        }
    </script>
</body>
</html>

 

index.html

 

loginPage.html

 

signupPage.html

 

728x90

댓글