반응형


쿠키는 브라우저에 정보들을 저장하는 방식으로 진행된다



세션은 정보를 서버에 저장해놓고 키를 통해서 브라우저와 통신하게 되는데

이때 필요한 세션정보는 쿠키로 저장한다 => (connect.id)



Route 에 의한 경로 이동을 하게 되는데 html 에서는 action="path" 에 있는 경로나  a href="path" 에 있는 경로를 보고


서버(Nodejs) 로 해당 경로를 던지게 되면 서버(Nodejs) 에서는 해당 경로를 Route 로 등록해놓았을 경우


해당 경로에 대한 함수 처리를 하게 되는 방식으로 동작한다




세션을 통한 전체 동작은 다음 처럼 이루어진다


로그인하여 product.html 에 있는 내용을 보기위한 과정이라고 보면된다(로그인처리하면서 정보를 세션에 저장)

다 보았으면 로그아웃하면서 세센 정보를 삭제한다



(html 파일들은 public  폴더 아래 있다고 가정한다)







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
<!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>
            </tr>
 
        </table>
 
    </form>
 
</body>
</html>






Product.html  (간단한 shoes 정보를 보여준다고 가정하는 페이지)



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
 
<html>
<head>
    <meta charset="utf-8" />
    <title>product</title>
</head>
<body>
    <h3>product page - Now sale</h3>
    <br />
 
    <p>Nice shoes 1</p>
    <p>Nice shoes 2</p>
    <p>Nice shoes 3</p>
    <p>Nice shoes 4</p>
    <p>Nice shoes 5</p>
 
    <a href="/process/logout"> Logout  </a>
</body>
</html>






서버코드 (Nodejs.js)



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
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 app = express();      //express 서버 객체
 
var bodyParser_post = require('body-parser');       //post 방식 파서
 
app.set('port'3000);
 
 
//미들웨어들 등록 시작, 아래 미들웨어들은 내부적으로 next() 가실행됨
 
//join은 __dirname : 현재 .js 파일의 path 와 public 을 합친다
//이렇게 경로를 세팅하면 public 폴더 안에 있는것을 곧바로 쓸 수 있게된다
app.use(serveStatic(path.join(__dirname, 'public')));
 
 
//post 방식 일경우 begin
//post 의 방식은 url 에 추가하는 방식이 아니고 body 라는 곳에 추가하여 전송하는 방식
app.use(bodyParser_post.urlencoded({ extended: false }));            // post 방식 세팅
app.use(bodyParser_post.json());                                     // json 사용 하는 경우의 세팅
//post 방식 일경우 end
 
 
 
//쿠키와 세션을 미들웨어로 등록한다
app.use(cookieParser());
 
//세션 환경 세팅
//세션은 서버쪽에 저장하는 것을 말하는데, 파일로 저장 할 수도 있고 레디스라고 하는 메모리DB등 다양한 저장소에 저장 할 수가 있는데
app.use(expressSession({
    secret: 'my key',           //이때의 옵션은 세션에 세이브 정보를 저장할때 할때 파일을 만들꺼냐 //아니면 미리 만들어 놓을꺼냐 등에 대한 옵션들임
    resave: true,
    saveUninitialized:true
}));
 
 
 
//라우트를 미들웨어에 등록하기 전에 라우터에 설정할 경로와 함수를 등록한다
//
//라우터를 사용 (특정 경로로 들어오는 요청에 대하여 함수를 수행 시킬 수가 있는 기능을 express 가 제공해 주는것)
var router = express.Router();
 
 
//http://localhost:3000/process/product 이 주소로 치면 라우터를 통해 바로 여기로 올 수 있다
router.route('/process/product').get(
    function (req, res)
    {
        console.log('/process/product  라우팅 함수 실행');
 
        //세션정보는 req.session 에 들어 있다
        if (req.session.user)       //세션에 유저가 있다면
        {
            res.redirect('/product.html');
        }
        else
        {
            res.redirect('/login2.html');
 
        }
    }
);
 
router.route('/process/login').post(                      //설정된 쿠키정보를 본다
    function (req, res) {
        console.log('/process/login 라우팅 함수호출 됨');
 
        var paramID = req.body.id || req.query.id;
        var pw = req.body.passwords || req.query.passwords;
 
        if (req.session.user) {
            console.log('이미 로그인 되어 있음');
 
            res.writeHead(200, { "Content-Type""text/html;characterset=utf8" });
            res.write('<h1>already Login</h1>');
            res.write('[ID] : ' + paramID + ' [PW] : ' + pw);
            res.write('<a href="/process/product">Move</a>');
            res.end();
 
        } else {
            req.session.user =
                {
                    id: paramID,
                    pw: pw,
                    name'UsersNames!!!!!',
                    authorized: true
                };
            res.writeHead(200, { "Content-Type""text/html;characterset=utf8" });
            res.write('<h1>Login Success</h1>');
            res.write('[ID] : ' + paramID + ' [PW] : ' + pw);
            res.write('<a href="/process/product">Move</a>');
            res.end();
        }
    }
);
 
router.route('/process/logout').get(                      //설정된 쿠키정보를 본다
    function (req, res) {
        console.log('/process/loginout 라우팅 함수호출 됨');
 
        if (req.session.user) {
            console.log('로그아웃 처리');
            req.session.destroy(
                function (err) {
                    if (err) {
                        console.log('세션 삭제시 에러');
                        return;
                    }
                    console.log('세션 삭제 성공');
                    //파일 지정시 제일 앞에 / 를 붙여야 root 즉 public 안에서부터 찾게 된다
                    res.redirect('/Login2.html');
                }
            );          //세션정보 삭제
 
        } else {
            console.log('로긴 안되어 있음');
            res.redirect('/Login2.html');
        }
 
 
     
    }
);
 
 
//라우터 미들웨어 등록하는 구간에서는 라우터를 모두  등록한 이후에 다른 것을 세팅한다
//그렇지 않으면 순서상 라우터 이외에 다른것이 먼저 실행될 수 있다
app.use('/', router);       //라우트 미들웨어를 등록한다
 
 
app.all('*',
    function (req, res) {
        res.status(404).send('<h1> 요청 페이지 없음 </h1>');
    }
);
 
//웹서버를 app 기반으로 생성
var appServer = http.createServer(app);
appServer.listen(app.get('port'),
    function () {
        console.log('express 웹서버 실행' + app.get('port'));
    }
);
 


반응형

+ Recent posts