### # Node.js-Express
### # 참고 : https://velopert.com/379
### # 디렉토리 구조
express_tutorial/
├── data
│ └── user.json
├── node_modules
├── package.json
├── public
│ └── css
│ └── style.css
├── router
│ └── main.js
├── server.js
└── views
├── body.ejs
├── header.ejs
└── index.ejs
### # 의존 모듈 추가
```
{
"name": "express-tutorial",
"version": "1.0.0",
"dependencies":
{
"express": "~4.13.1",
"ejs": "~2.4.1"
}
}
```
▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼
```
{
"name": "express-tutorial",
"version": "1.0.0",
"dependencies":
{
"express": "~4.13.1",
"ejs": "~2.4.1" ,
"body-parser": "~1.14.2",
"express-session": "~1.13.0"
}
}
```
### # NPM package.json을 이용한 의존 패키지 설치
```
$ npm install
```
### # server.js
```
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var session = require('express-session');
var fs = require("fs")
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
var server = app.listen(3000, function(){
console.log("Express server has started on port 3000")
});
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(session({
secret: '@#@$MYSIGN#@$#$',
resave: false,
saveUninitialized: true
}));
var router = require('./router/main')(app, fs);
```
### # 테스트 : http://localhost:3000/
### # /router/main.js
```
module.exports = function(app)
{
app.get('/',function(req,res){
res.render('index.html')
});
app.get('/about',function(req,res){
res.render('about.html');
});
}
```
### # HTML views/index.html & about.html 생성
```html
<html>
<head>
<title>Main</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
Hey, this is index page
</body>
</html>
and
<html>
<head>
<title>About</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
About... what?
</body>
</html>
```
### # server.js
```
var express = require('express');
var app = express();
var router = require('./router/main')(app); // router 모듈을 app에 적용.
app.set('views', __dirname + '/views'); // html 위치 정의
app.set('view engine', 'ejs'); // 서버가 HTML 렌더링에 EJS엔진을 사용하도록 설정.
app.engine('html', require('ejs').renderFile);
var server = app.listen(3000, function(){
console.log("Express server has started on port 3000")
});
```
### # Static files --> express.static()
- HTML의 .js , css , image 등의 리소스파일.
- express.static()
- public/css/style.css 파일 생성
```css
body{
background-color: black;
color: white;
}
```
- server.js 아래에 코드 추가
- app.use(express.static('public'));
- $ node server.js
- http://localhost:3000/
---
### # view/body.ejs
```jsp
<h1>Loop it!</h1>
<ul>
<% for(var i=0; i<length; i++){ %>
<li>
<%= "LOOP" + i %>
</li>
<% } %>
</ul>
<% if(username){ %>
<h2>Welcome! <%= username %> (name: <%= name %>)</h2>
<% }else{ %>
<h2> Please Login. </h2>
<% } %>
```
### # data/user.js
```
{
"first_user": {
"password": "first_pass",
"name": "abet"
},
"second_user":{
"password": "second_pass",
"name": "betty"
},
"test":{
"password": "1234",
"name": "tester"
}
}
```
### # server.js
```
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var session = require('express-session');
var fs = require("fs")
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
var server = app.listen(3000, function(){
console.log("Express server has started on port 3000")
});
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(session({
secret: '@#@$MYSIGN#@$#$',
resave: false,
saveUninitialized: true
}));
var router = require('./router/main')(app, fs);
```
### # main.js
```
module.exports = function(app, fs)
{
app.get('/',function(req,res){
var sess = req.session;
res.render('index', {
title: "MY HOMEPAGE",
length: 5,
name: sess.name,
username: sess.username
})
});
app.get('/list', function (req, res) {
fs.readFile( __dirname + "/../data/user.json", 'utf8', function (err, data) {
console.log( data );
res.end( data );
});
});
app.get('/getUser/:username', function(req, res){
fs.readFile( __dirname + "/../data/user.json", 'utf8', function (err, data) {
var users = JSON.parse(data);
res.json(users[req.params.username]);
});
});
app.post('/addUser/:username', function(req, res){
var result = { };
var username = req.params.username;
// CHECK REQ VALIDITY
if(!req.body["password"] || !req.body["name"]){
result["success"] = 0;
result["error"] = "invalid request";
res.json(result);
return;
}
// LOAD DATA & CHECK DUPLICATION
fs.readFile( __dirname + "/../data/user.json", 'utf8', function(err, data){
var users = JSON.parse(data);
if(users[username]){
// DUPLICATION FOUND
result["success"] = 0;
result["error"] = "duplicate";
res.json(result);
return;
}
// ADD TO DATA
users[username] = req.body;
// SAVE DATA
fs.writeFile(__dirname + "/../data/user.json",
JSON.stringify(users, null, '\t'), "utf8", function(err, data){
result = {"success": 1};
res.json(result);
})
})
});
app.put('/updateUser/:username', function(req, res){
var result = { };
var username = req.params.username;
// CHECK REQ VALIDITY
if(!req.body["password"] || !req.body["name"]){
result["success"] = 0;
result["error"] = "invalid request";
res.json(result);
return;
}
// LOAD DATA
fs.readFile( __dirname + "/../data/user.json", 'utf8', function(err, data){
var users = JSON.parse(data);
// ADD/MODIFY DATA
users[username] = req.body;
// SAVE DATA
fs.writeFile(__dirname + "/../data/user.json",
JSON.stringify(users, null, '\t'), "utf8", function(err, data){
result = {"success": 1};
res.json(result);
})
})
});
app.delete('/deleteUser/:username', function(req, res){
var result = { };
//LOAD DATA
fs.readFile(__dirname + "/../data/user.json", "utf8", function(err, data){
var users = JSON.parse(data);
// IF NOT FOUND
if(!users[req.params.username]){
result["success"] = 0;
result["error"] = "not found";
res.json(result);
return;
}
// DELETE FROM DATA
delete users[req.params.username];
// SAVE FILE
fs.writeFile(__dirname + "/../data/user.json",
JSON.stringify(users, null, '\t'), "utf8", function(err, data){
result["success"] = 1;
res.json(result);
return;
})
})
})
app.get('/login/:username/:password', function(req, res){
var sess;
sess = req.session;
fs.readFile(__dirname + "/../data/user.json", "utf8", function(err, data){
var users = JSON.parse(data);
var username = req.params.username;
var password = req.params.password;
var result = {};
if(!users[username]){
// USERNAME NOT FOUND
result["success"] = 0;
result["error"] = "not found";
res.json(result);
return;
}
if(users[username]["password"] == password){
result["success"] = 1;
sess.username = username;
sess.name = users[username]["name"];
res.json(result);
}else{
result["success"] = 0;
result["error"] = "incorrect";
res.json(result);
}
})
});
app.get('/logout', function(req, res){
sess = req.session;
if(sess.username){
req.session.destroy(function(err){
if(err){
console.log(err);
}else{
res.redirect('/');
}
})
}else{
res.redirect('/');
}
})
}
```
'web > javascript' 카테고리의 다른 글
Node.js - Http Module (0) | 2019.07.24 |
---|---|
Node.js - events Module & EventEmitter Class (0) | 2019.07.23 |
Node.js (0) | 2019.07.21 |
Fullscreen (0) | 2019.07.19 |
jquery model dialog box (0) | 2019.07.18 |
댓글