본문 바로가기

JS/NodeJS

Node JS로 단순 간단한 즐겨찾기 사이트 만들기 + MongoDB

몽고 DB를 쓰기 위해 mongoose 모듈 추가해야 함


bookmark.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
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>즐겨찾기 추가</title>
    </head>
<body>
    <h1>즐겨찾기 추가</h1>
    <br>
    <form method="post" enctype="multipart/form-data" action="/process/bookmark">
        <div>
            <table>
                <tr>
                    <th>사이트 주소</th><th>명칭</th><th>대표 이미지</th>
                </tr>
                <tr>
                    <td><input type="input" name="bookmarkUrl"/></td>
                    <td><input type="input" name="bookmarkName"/></td>
                    <td><input type="file" name="bookmarkImg" /></td>
                </tr>
            </table>
            <input type="submit" value="추가" name="submit"/>
        </div>
    </form>
    <hr>
    <form method="post" action="/process/siteview">
        <input type="submit" value="즐겨찾기 보기" name=submit2/>
    </form>
</body>
</html>
cs


404.html

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>에러 페이지</title>
    </head>
<body>
    <h3>ERROR - 페이지를 찾을 수 없습니다.</h3>
    <hr/>
    <p>/public/404.html 파일의 에러 페이지를 표시한 것입니다.</p>
</body>
</html>
cs


app.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
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
// Express 기본 모듈 불러오기
var express = require('express')
  , http = require('http')
  , path = require('path');
 
// Express의 미들웨어 불러오기
var bodyParser = require('body-parser')
  , cookieParser = require('cookie-parser')
  , static = require('serve-static')
  , errorHandler = require('errorhandler');
 
// 에러 핸들러 모듈 사용
var expressErrorHandler = require('express-error-handler');
 
// Session 미들웨어 불러오기
var expressSession = require('express-session');
 
// 파일 업로드용 미들웨어
var multer = require('multer');
var fs = require('fs');
 
//클라이언트에서 ajax로 요청 시 CORS(다중 서버 접속) 지원
var cors = require('cors');
 
 
// 익스프레스 객체 생성
var app = express();
var mongoose=require('mongoose');
//db 객체
var database;
//db 스키마 객체
var BookmarkSchema;
//db 모델 객체
var BookmarkModel;
// 기본 속성 설정
app.set('port', process.env.PORT || 3000);
 
// body-parser를 이용해 application/x-www-form-urlencoded 파싱
app.use(bodyParser.urlencoded({ extended: false }))
 
// body-parser를 이용해 application/json 파싱
app.use(bodyParser.json())
 
// public 폴더와 uploads 폴더 오픈
app.use('/public', static(path.join(__dirname, 'public')));
app.use('/uploads', static(path.join(__dirname, 'uploads')));
 
// cookie-parser 설정
app.use(cookieParser());
 
// 세션 설정
app.use(expressSession({
    secret:'my key',
    resave:true,
    saveUninitialized:true
}));
 
 
//클라이언트에서 ajax로 요청 시 CORS(다중 서버 접속) 지원
app.use(cors());
 
//multer 미들웨어 사용 : 미들웨어 사용 순서 중요  body-parser -> multer -> router
// 파일 제한 : 10개, 1G
var storage = multer.diskStorage({
    destination: function (req, file, callback) {
        callback(null'uploads')
    },
    filename: function (req, file, callback) {
        callback(null, file.originalname)
    }
});
 
var upload = multer({ 
    storage: storage,
    limits: {
        files: 10,
        fileSize: 1024 * 1024 * 1024
    }
});
 
function connectDB(){
    var databaseUrl="mongodb://localhost:27017/local";
    console.log('db연결');
    mongoose.Promise=global.Promise;
    mongoose.connect(databaseUrl,{useNewUrlParser:true});
    database=mongoose.connection;
    
    database.on('error',console.error.bind(console,'mongoose connection error'));
    database.on('open',function(){
        console.log('db에 연결됨:'+databaseUrl);
        BookmarkSchema=mongoose.Schema({
            bmurl:String,
            bmname:String,
            bmimage:String
        });
        console.log('BookmarkSchema 정의함');
        //BookmarkModel 정의
        BookmarkModel=mongoose.model('bookmarks',BookmarkSchema);
        console.log('BookmarkModel 정의함');
    });
    database.on('disconnected',function(){
        console.log('연결이 끊어짐 5초후 재 연결');
        setInterval(connectDB,5000);
    });
}
 
var addBookmark=function(database,bmurl,bmname,bmimage,callback){
    console.log('addBookmark 호출됨: '+bmurl+', '+bmname+', '+bmimage);
    var bm=new BookmarkModel({"bmurl":bmurl,"bmname":bmname,"bmimage":bmimage});
    bm.save(function(err){
        if(err){
            callback(err,null);
            return;
        }
        console.log('사이트 추가함');
        callback(null,bm);
    });
};
 
var siteViewer=function(database,callback){
    console.log('siteViewer 호출됨');
    BookmarkModel.find({},function(err,results){
        if(err){
            callback(err,null);
            return;
        }
        //console.log('즐겨찾기 검색 결과: ');
        //console.dir(results);
        if(results.length>0){
            console.log('즐겨찾기 찾음');
            callback(null,results);
        }else{
            console.log('즐겨찾기 못찾음');
            callback(null,null);
        }
    });
};
// 라우터 사용하여 라우팅 함수 등록
var router = express.Router();
 
// 파일 업로드 라우팅 함수 - 로그인 후 세션 저장함
router.route('/process/bookmark').post(upload.array('bookmarkImg'1), function(req, res) {
    console.log('/process/bookmark 호출됨.');
    try{
        var paramUrl=req.body.bookmarkUrl;
        var paramName=req.body.bookmarkName;
        var file=req.files;
        var imgpath=file[0].path;
        console.log('file정보: ');
        console.log(file);
        console.log(imgpath);
        //console.dir('파일 정보: '+req.file[0]);
        console.log('요청 파라미터들:'+paramUrl+', '+paramName);
 
        if(database){
            addBookmark(database,paramUrl,paramName,imgpath,function(err,result){
                if(err) throw err;
                if(result){
                    console.dir(result);
                    res.writeHead('200',{'Content-Type':'text/html;charset=utf8'});
                    res.write('<h2>사이트 추가 성공</h2>');
                    res.write('<a href="/public/bookmark.html">즐겨찾기 추가 페이지로 돌아가기</a>');
                    res.end();
                }else{
                    res.writeHead('200',{'Content-Type':'text/html;charset=utf8'});
                    res.write('<h2>사이트 추가 실패</h2>');
                    console.dir(result);
                    res.end();
                }
            });
        }else{
            res.writeHead('200',{'Content-Type':'text/html;charset=utf8'});
            res.write('<h2>db 연결 실패</h2>');
            res.end();
        }
    }catch(err) {
        console.dir(err.stack);
    }            
});
 
router.route('/process/siteview').post(function(req,res){
    console.log('즐겨찾기 보기, siteViewer() 호출');
    if(database){
        siteViewer(database,function(err,results){//즐겨찾기 찾으면 callback으로 results받아옴
            res.writeHead('200',{'Content-Type':'text/html;charset=utf8'});
            res.write('<h1>나의 즐겨찾기 보기</h1>');
            res.write('<table border=1><tr><th>즐겨찾기</th><th>이미지</th></tr>');
            
            for(var i=0;i<results.length;i++){
                res.write('<tr>');
                res.write('<td><a href="'+results[i].bmurl+'">'+results[i].bmname+'</a></td>'+
                          '<td><img width="80" height="80" src="../'+results[i].bmimage+'"/></td>');
                res.write('</tr>');
            }
            res.write('</table>');
            res.end();
        });
    }
});
 
app.use('/', router);
// 404 에러 페이지 처리
var errorHandler = expressErrorHandler({
    static: {
      '404''./public/404.html'
    }
});
 
app.use( expressErrorHandler.httpError(404) );
app.use( errorHandler );
 
// Express 서버 시작
http.createServer(app).listen(app.get('port'), function(){
    console.log('Express server listening on port ' + app.get('port'));
    connectDB();
});
cs



mongoDB database


즐겨찾기 추가하는 화면

사이트 주소 입력하고 기억하기 쉽게 명칭, 대표 이미지 넣기

mongodb database에 data 들어감


즐겨찾기 보기 클릭하면 적용된게 나옴