반응형


Mysql & nodejs 로 가입, 로그인 처리하기(관계형 데이터베이스 사용)










[Mysql + HeidiSQL + nodejs(express, 각종 모듈) 조합]



소스는 연습을 위한 코드임으로 날림주의!


Nodejs 에서 관계형 데이터 베이스 사용


MySQL, Oracle 등에서 사용하는 구조



데이터베이스  테이블 집합의 형태





데이터베이스로 연결 및 사용하는 방법






MySQL 을 사용하기 위해선 먼저 프로그램이 필요함

https://dev.mysql.com/downloads/


https://dev.mysql.com/downloads/mysql/




heidisql 을 설치(프리)

https://www.heidisql.com/screenshots.php?which=query




 상단에 데이터 탭을 선택하면 추가된 데이터또한 볼 수 있다


heidisql 로 좀 더 간편하게 데이터베이스를 조작할 수 있다



localhost 로 접속하여 기본 데이터 베이스 필드 만들고  DB명 test, 테이블 명 users


DB : test  생성 후 test 에서 오른족 버튼 클릭 새로생성 -> table   로 테이블 생성

필드는 아래처럼





id 를 Primary key 로 설정해주면 중복가입을 막을 수 있다


아래는 id 를 primary 를 적용한 모습

테이블 탭에서 id 를 primary key 로 적용 할 수 있다(데이터 추가는 서버 실행 시키고 난 이후 가입 정보를 입력하여 등록된 정보들이다








1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<!DOCTYPE html>
 
<html>
<head>
    <meta charset="utf-8" />
    <title>login2</title>
</head>
<body>
 
    <h1>login2</h1>
    <form method="post" action="/process/Login">
        <table>
            <tr>
                <td><label>ID : </label></td>
                <td><input type="text" name="id"></td>
            </tr>
            <tr>
                <td><label>PW : </label></td>
                <td><input type="text" name="passwords"></td>
 
 
            </tr>
 
            <tr>
                <td><input type="submit" value="Sumit" name=""></td>
                <td><input type="button" value="Join" onclick="location.href='/addUser2.html'"></td>
            </tr>
 
        </table>
 
    </form>
 
</body>
</html>


login2.html










1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE html>
 
<html>
<head>
    <meta charset="utf-8" />
    <title>Add User</title>
</head>
<body>
 
    <h1>Add User</h1>
    <form method="post" action="/process/addUser">
        <table>
            <tr>
                <td><label>ID : </label></td>
                <td><input type="text" name="id"></td>
            </tr>
            <tr>
                <td><label>PW : </label></td>
                <td><input type="text" name="passwords"></td>
            </tr>
 
            <tr>
                <td><label>name : </label></td>
                <td><input type="text" name="name"></td>
            </tr>
 
            <tr>
                <td><label>age : </label></td>
                <td><input type="text" name="age"></td>
            </tr>
 
            <tr>
                <td><input type="submit" value="Sumit" name=""></td>
                <td><input type="button" value="Login" onclick="location.href='/Login2.html'"></td>
            </tr>
 
        </table>
 
    </form>
 
</body>
</html>



addUser2.html








서버코드


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
var express = require('express');
var http = require('http');
var serveStatic = require('serve-static');      //특정 폴더의 파일들을 특정 패스로 접근할 수 있도록 열어주는 역할
var path = require('path');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var expressErrorHandler = require('express-error-handler');
 
 
var mySql = require('mysql');
 
//connection 은 한정되어 있어서 풀을 만들어 그 안에서 사용한다
//connection 할때도 비용이 들어감, 만들고 닫고
 
var pool = mySql.createPool({
    connectionLimit: 10,            //접속을 10개 만들고 10개를 재사용
    host: 'localhost',
    user:'root',
    password: '00000', //MySql 설치할때의 비번을 입력하면 됨!!
    database: 'test',
    debug: false
 
});
 
 
 
var app = express();      //express 서버 객체
 
 
app.set('port'3000);
app.use(serveStatic(path.join('public', __dirname, 'public')));
 
 
 
var bodyParser_post = require('body-parser');       //post 방식 파서
//post 방식 일경우 begin
//post 의 방식은 url 에 추가하는 방식이 아니고 body 라는 곳에 추가하여 전송하는 방식
app.use(bodyParser_post.urlencoded({ extended: false }));            // post 방식 세팅
app.use(bodyParser_post.json());                                     // json 사용 하는 경우의 세팅
//post 방식 일경우 end
 
 
 
app.use(serveStatic(path.join(__dirname, 'public')));
 
 
//쿠키와 세션을 미들웨어로 등록한다
app.use(cookieParser());
 
//세션 환경 세팅
//세션은 서버쪽에 저장하는 것을 말하는데, 파일로 저장 할 수도 있고 레디스라고 하는 메모리DB등 다양한 저장소에 저장 할 수가 있는데
app.use(expressSession({
    secret: 'my key',           //이때의 옵션은 세션에 세이브 정보를 저장할때 할때 파일을 만들꺼냐 , 아니면 미리 만들어 놓을꺼냐 등에 대한 옵션들임
    resave: true,
    saveUninitialized: true
}));
 
 
 
 
//라우트를 미들웨어에 등록하기 전에 라우터에 설정할 경로와 함수를 등록한다
//
//라우터를 사용 (특정 경로로 들어오는 요청에 대하여 함수를 수행 시킬 수가 있는 기능을 express 가 제공해 주는것)
var router = express.Router();
 
 
router.route('/process/addUser').post(
    function (req, res)
    {
        console.log('process/addUser 호출됨');
        var paramID = req.body.id || req.query.id;
        var paramPW = req.body.passwords || req.query.passwords;
        var paramName = req.body.name || req.query.name;
        var paramAge = Number(req.body.age || req.query.age);
        console.log('id:' + paramID + ', paramPW: ' + paramPW + ' ,paramName: ' + paramName + ' ,paramAge: ' + paramAge);
 
        addUser(paramID, paramName, paramAge, paramPW,
            function (err, result) {
                if (err) {
                    console.log('Error!!!');
                    res.writeHead(200, { "Content-Type""text/html;charset=utf-8" });
                    res.write('<h1>에러발생 - 이미 존재하는  아이디일수 있음</h1>');
                    res.write('<br><a href="/login2.html"> re login </a>');
                    res.end();
                    return;
                }
 
                if (result)
                {
                    console.dir(result);
                    res.writeHead(200, { "Content-Type""text/html;charset=utf-8" });
                    res.write('<h1>Add Success</h1>');
                    res.write('<br><a href="/login2.html"> re login </a>');
                    res.end();
                }
                else
                {
                    console.log('데이터베이스에 추가 에러');
                    res.writeHead(200, { "Content-Type""text/html;charset=utf-8" });
                    res.write('<h1> Failed : add user</h1>');
                    res.write('<a href="/login2.html"> re login</a>');
                    res.end();
                }
            }
        );
    }
);
 
 
 
router.route('/process/login').post(
    function (req, res) {
        console.log('process/login 호출됨');
        var paramID = req.body.id || req.query.id;
        var paramPW = req.body.passwords || req.query.passwords;
        console.log('paramID : ' + paramID + ', paramPW : ' + paramPW);
 
        authUser( paramID, paramPW,
            function (err, rows)
            {
                if (err) {
                    console.log('Error!!!');
                    res.writeHead(200, { "Content-Type""text/html;charset=utf-8" });
                    res.write('<h1>에러발생</h1>');
                    res.end();
                    return;
                }
 
                if (rows) {
                    console.dir(rows);
                    res.writeHead(200, { "Content-Type""text/html;charset=utf-8" });
                    res.write('<h1>Login Success</h1>');
                    res.write('<h1> user </h1>' + rows[0].name);
                    res.write('<br><a href="/login2.html"> re login </a>');
                    res.end();
 
                }
                else {
                    console.log('empty Error!!!');
                    res.writeHead(200, { "Content-Type""text/html;charset=utf-8" });
                    res.write('<h1>user data not exist</h1>');
                    res.write('<a href="/login2.html"> re login</a>');
                    res.end();
                }
            }
        );
    }
);
 
 
 
 
 
//라우터 미들웨어 등록하는 구간에서는 라우터를 모두  등록한 이후에 다른 것을 세팅한다
//그렇지 않으면 순서상 라우터 이외에 다른것이 먼저 실행될 수 있다
app.use('/', router);       //라우트 미들웨어를 등록한다
 
 
var addUser = function(id,name,age,passwords,callback)
{
    console.log('addUser 호출');
 
    //pool로 DB접근 함수 호출(mysql 접근)
    //conn 연결된 객체
    pool.getConnection(
        function (err, poolConn)
        {
            if (err)
            {
                if (poolConn) {
                    poolConn.release();        // 사용한후 해제(반납)한다
                }
                callback(err, null);
                return;
            }
            console.log('데이터베이스 연결 스레드 아이디' + poolConn.threadId);
            var data = { id: id, namename, age: age, passwords: passwords };
 
            //users 테이블에 데이터 추가
            var exec = poolConn.query('insert into users set ?', data,
                function (err, result)
                {
                    poolConn.release();
                    console.log('실행된 SQL : ' + exec.sql);
 
                    if (err) {
                        console.log('sql 실행 시 에러 발생');
                        callback(err, null);
                        return;
                    }
 
                    callback(null, result);
                }
            );
        }
    );
}
 
var authUser = function (id, password, callback) {
    console.log('input id :' + id + '  :  pw : ' + password);
 
 
    pool.getConnection(function (err, poolConn) {
        if (err) {
            if (poolConn) {
                poolConn.release();     //pool 반환처리
            }
 
            callback(err, null);
            return;
        }
 
        console.log('데이터베이스 연결 스레드 아이디' + poolConn.threadId);
 
        var tablename = 'users';
        var columns = ['id''name''age'];
 
 
        //id 와 pw 가 같은것을 조회한다
        var exec = poolConn.query("select ?? from ?? where id = ? and passwords=?", [columns, tablename, id, password],
 
            function (err, rows)
            {
                poolConn.release();     //pool 반환처리
                console.log('실행된 ssql : ' + exec.sql);
 
                if (err) {
                    callback(err, null);
                    return;
                }
 
                if (rows.length > 0) {
                    console.log('사용자 찾음');
                    callback(null, rows);
                } else {
                    console.log('사용자 찾지 못함');
                    callback(nullnull);
                }
 
            }
        );
 
    }
);
 
 
};
 
 
 
 
 
 
var errorHandler = expressErrorHandler(
    { static: { '404''./public/404.html' } }              //404 에러 코드가 발생하면 해당 페이지를 보여주는 예외 미들웨어
);
 
app.use(expressErrorHandler.httpError(404));
app.use(expressErrorHandler);
 
//웹서버를 app 기반으로 생성
var appServer = http.createServer(app);
appServer.listen(app.get('port'),
    function () {
        console.log('express 웹서버 실행' + app.get('port'));
    }
);
 



반응형

+ Recent posts