Nodejs

 

 

인프런 강의

https://www.inflearn.com/course/node-js-%EC%9B%B9%EA%B0%9C%EB%B0%9C#

 

 

Node.js, Express를 기반으로 한 웹애플리케이션 구축.
Template Engine
Ajax와 JSON을 활용한 RESTful API 기반 웹 서비스 기초.
Passport기반의 인증처리 방법.


소스코드 : https://github.com/crongro/node_server_inflearn
https://github.com/braverokmc79/node_server_inflearn

 

1. nodeJS + Express 웹서버 설정
1) NPM Project 시작하기
2) Express 기반 웹서버 구동
3) URL Routing 처리
4) static 디렉토리 설정

 

2. Request,Response 처리 기본
5) POST 요청처리
6) View engine을 활용한 응답처리
7) JSON 활용한 Ajax처리
중간 실습 과제 1

 

3. Database 연동 기본
8) MySQL 연동 설정
9) MySQL 연동 구현

 

4. Router 개선 - 모듈화
10) Routing 모듈화
11 )Routing 모듈화 2 (DB연결부분)
12) Routing 리팩토링

 

5. DB에 데이터추가
13) DB에 데이터추가 (create user) 1편
14) DB에 데이터추가 (create user) 2편
15) DB에 데이터추가 (create user) 3편


6. 패스포트기반 인증 로직 구현 (회원가입, 로그인, 로그아웃)
16) passport 환경구축
17) middleware,strategy 설정
18) passport 기반 router 설정
19) local-strategy 콜백완성
20) passport기반 세션처리
21) 로그인 로직 구현
22) Ajax 기반의 passport 인증처리
23) 로그아웃 처리
중간 실습 과제 2


7. RESTful API
24) RESTful API 정의
25) RESTful API GET
26) RESTful API POST
27) RESTful API GET SUB-URI
38) RESTful API DELETE

 

 

1. nodeJS + Express 웹서버 설정

 

 

1) NPM Project 시작하기

 

강의: https://www.inflearn.com/course/node-js-%EC%9B%B9%EA%B0%9C%EB%B0%9C/unit/6118?tab=curriculum

 

npm init → 계속 엔터 눌러서 설정 

 

 package.json 파일이 생성

 

터미널에서 npm install express --save 입력

 

 

 

 

 

2) Express 기반 웹서버 구동

 

강의 :  https://www.inflearn.com/course/node-js-%EC%9B%B9%EA%B0%9C%EB%B0%9C/unit/6119?tab=curriculum

 

app.js 파일 생성

const express = require('express');
const app = express();
app.listen(3000, function () {
    console.log("start! express server on port 3000");
});

console.log("end of server code....");

 

nodemon 설치

 

$  npm install nodemon -g

 

 

 

 

 

3) URL Routing 처리

강의 :  https://www.inflearn.com/course/node-js-%EC%9B%B9%EA%B0%9C%EB%B0%9C/unit/6120?tab=curriculum

 

app.js

const express = require('express');
const app = express();
app.listen(3000, function () {
    console.log("start! express server on port 3000");
});


app.get("/", function (req, res) {
    //res.send("<h1>h1 friend</h1>");
    res.sendFile(__dirname + "/public/main.html");
})

 

 

public/main.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>main.html</title>
</head>
<body>

    <h1>메인 페이지</h1>
    
</body>
</html>

 

 

 

 

4) static 디렉토리 설정

 

강의 https://www.inflearn.com/course/node-js-%EC%9B%B9%EA%B0%9C%EB%B0%9C/unit/6121?tab=curriculum

 

const express = require('express');
const app = express();
app.listen(3000, function () {
    console.log("start! express server on port 3000");
});

//static 파일 등록 처리
app.use(express.static("public"));


app.get("/", function (req, res) {
    console.log("test");
    //res.send("<h1>h1 friend</h1>");
    res.sendFile(__dirname + "/public/main.html");
})

app.get("/main", function (req, res) {
    res.sendFile(__dirname + "/public/main.html");
})

 

 

 

 

 

 

 

 2. Request,Response 처리 기본

 

 

 

5) POST 요청처리

 

강의 https://www.inflearn.com/course/node-js-%EC%9B%B9%EA%B0%9C%EB%B0%9C/unit/6123?tab=curriculum

 

설치

$ npm i body-parser

 

 

사용

const app = express();
app.use(bodyParser.urlencoded({ extended: true }));

또는

app.use(bodyParser().json())

 

 

=>1 . body-parser 업그레이드

.

express.js도 빌트인 body parser를 넣었다는 점을 알게 되었습니다.(Express v4.16.0 기준

그래서 다음과 같이 써도 문제는 해결됩니다.

.

var express = require('express')
var app = express();
app.use(express.json())app.post('/profile', function(req, res) => {
  console.log(req.body)
})

.

=>2.  body-parser 업그레이드

 

Express 쓸 때, 바디 파서를 따로 임포트하지 않아도 된다.

 

var express = require('express')
var app = express();


app.use(express.json())
//둘다 또는 
app.use(express.urlencoded({ extended: true }));


app.post('/profile', function(req, res) => {
  console.log(req.body)
})

 

 

 

app.js

const express = require('express');
//const bodyParser = require('body-parser')
const app = express();

app.listen(3000, function () {
    console.log("start! express server on port 3000");
});

//static 파일 등록 처리
app.use(express.static("public"));
//app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.get("/", function (req, res) {
    console.log("test");
    //res.send("<h1>h1 friend</h1>");
    res.sendFile(__dirname + "/public/main.html");
});

app.get("/main", function (req, res) {
    res.sendFile(__dirname + "/public/main.html");
});



app.post("/email_post", function (req, res) {
    console.log("req.body : ", req.body.email);
    res.send(`<h1>welcome! ${req.body.email}</h1>`);
});

 

 

public/form.html

<!DOCTYPE html>
<html lang="en">
<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>email form</title>
</head>
<body>
    <form action="/email_post" method="post">
        email :  <input type="text" name="email"><br/>
        submit : <input type="submit">
    </form>
    

</body>
</html>

 

 

 

 

 

6) View engine을 활용한 응답처리

 

강의 https://www.inflearn.com/course/node-js-%EC%9B%B9%EA%B0%9C%EB%B0%9C/unit/6124?tab=curriculum

 

뷰 엔진은   ejs 사용

 

설치

 

$ npm install ejs

 

views 디렉토리에 파일 생성

다음과 같이 사용

app.set('view engine', 'ejs');



app.post("/email_post", function (req, res) {

    //view 디렉토리 인식
    res.render('email.ejs', { 'email': req.body.email })
});

 

 

app.js

const express = require('express');
//const bodyParser = require('body-parser')
const app = express();

app.listen(3000, function () {
    console.log("start! express server on port 3000");
});

//static 파일 등록 처리
app.use(express.static("public"));
//app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.set('view engine', 'ejs');


app.get("/", function (req, res) {
    console.log("test");
    //res.send("<h1>h1 friend</h1>");
    res.sendFile(__dirname + "/public/main.html");
});

app.get("/main", function (req, res) {
    res.sendFile(__dirname + "/public/main.html");
});



app.post("/email_post", function (req, res) {
    console.log("req.body : ", req.body.email);
    //res.send(`<h1>welcome! ${req.body.email}</h1>`);
    res.render('email.ejs', { 'email': req.body.email })
});


 

 

 

views/email.ejs

<!DOCTYPE html>
<html lang="en">
<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>email ejs</title>
</head>
<body>
    
    <h1>Welcome !! <%= email %></h1>
    <p>정말로 반가워요 ^^</p>
    
    
</body>
</html>

 

 

 

 

 

 

 

7) JSON 활용한 Ajax처리

 

강의 https://www.inflearn.com/course/node-js-%EC%9B%B9%EA%B0%9C%EB%B0%9C/unit/6125?tab=curriculum

 

app.js

 

const express = require('express');
//const bodyParser = require('body-parser')
const app = express();

app.listen(3000, function () {
    console.log("start! express server on port 3000");
});

//static 파일 등록 처리
app.use(express.static("public"));
//app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.set('view engine', 'ejs');

~


app.post("/ajax_send_email", function (req, res) {
    console.log("ajax_send_email - req.body : ", req.body.email);
    //check validation about input value => select db
    var responseData = { 'result': 'ok', 'email': req.body.email };
    res.status(200).json(responseData);
});

 

 

public/form.html

<!DOCTYPE html>
<html lang="en">
<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>email form</title>
</head>
<body>
    <form action="/email_post" method="post">
        email :  <input type="text" name="email"><br/>
        submit : <input type="submit">
    </form>
    
    <button class="ajaxsend">ajaxsend</button>

    <div class="result"></div>
    <script>
        document.querySelector('.ajaxsend').addEventListener('click',function(){
            var inputdata =document.forms[0].elements[0].value;
            sendAjax('/ajax_send_email',inputdata);
        });
/*
        function sendAjax(url, data){
            var data={'email':data};
            data=JSON.stringify(data);

            var xhr =new XMLHttpRequest();
            xhr.open('POST', url);
            xhr.setRequestHeader('Content-Type','application/json');
            xhr.send(data);

            xhr.addEventListener('load', function(){
                console.log(xhr.responseText);
                var result=JSON.parse(xhr.responseText);
                console.log("result  :",result);
                if(result.result!=="ok")return;
                document.querySelector(".result").innerHTML=result.email;
            });
        }
*/        
        function sendAjax(url, data){
            fetch(url, {
                headers:{'Content-Type' :"application/json"},
                method:"POST",
                body:JSON.stringify({'email':data})
            }) .then(res=>res.json())  
            .then(res=>{
                if(res.result!=="ok")return;
                document.querySelector(".result").innerHTML=res.email;
            }).catch(err=>console.error("에러:",err));
        }
    </script>

</body>
</html>

 

 

 

 

 

 

 

3. Database 연동 기본

 

 

8) MySQL 연동 설정

 

강의 :  https://www.inflearn.com/course/node-js-%EC%9B%B9%EA%B0%9C%EB%B0%9C/unit/6129?tab=curriculum

 

mysql 설치  : https://www.npmjs.com/package/mysql

 

DB 생성 및 테이블 생성 유저 생성  및 유저권한 부여

create user `node_inflearn`@`localhost` identified by '1111';
  
create database node_inflearn CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
  
grant all privileges on node_inflearn.* to `node_inflearn`@`localhost` ;


CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) ,
  `email` varchar(30) unique NOT NULL,
  `password` varchar(100),
  PRIMARY KEY (`id`)
)ENGINE=InnoDB  DEFAULT CHARSET=utf8mb4;

 

접속

app.js

const express = require('express');
//const bodyParser = require('body-parser')
const mysql = require('mysql');
const db = mysql.createConnection({
    host: 'localhost',
    user: 'node_inflearn',
    password: '1111',
    database: 'node_inflearn'
});
db.connect();
console.log("db 접속 :", db);


const app = express();

~

 

 

 

 

9) MySQL 연동 구현

 

강의 :  https://www.inflearn.com/course/node-js-%EC%9B%B9%EA%B0%9C%EB%B0%9C/unit/6130?tab=curriculum

 

 

app.js

const express = require('express');
//const bodyParser = require('body-parser')
const mysql = require('mysql');
const db = mysql.createConnection({
    host: 'localhost',
    user: 'node_inflearn',
    password: '1111',
    database: 'node_inflearn'
});
db.connect();
//console.log("db 접속 :", db);


const app = express();

app.listen(3000, function () {
    console.log("start! express server on port 3000");
});

//static 파일 등록 처리
app.use(express.static("public"));
//app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.set('view engine', 'ejs');


~


app.post("/ajax_send_email", function (req, res) {
    console.log("ajax_send_email - req.body : ", req.body.email);
    //check validation about input value => select db

    db.query("select name from users where email =?", [req.body.email], function (err, rows) {
        if (err) return res.status(400).json({ err: err });
        if (rows[0]) return res.status(200).json({ result: "ok", name: rows[0].name })
        else return res.status(200).json({ result: "none", name: "" })
    });
});

 

 

 

public/form.html

<!DOCTYPE html>
<html lang="en">
<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>email form</title>
</head>
<body>
    <form action="/email_post" method="post">
        email :  <input type="text" name="email"><br/>
        submit : <input type="submit">
    </form>
    
    <button class="ajaxsend">ajaxsend</button>

    <div class="result"></div>
    <script>
        document.querySelector('.ajaxsend').addEventListener('click',function(){
            var inputdata =document.forms[0].elements[0].value;
            sendAjax('/ajax_send_email',inputdata);
        });
/*
        function sendAjax(url, data){
            var data={'email':data};
            data=JSON.stringify(data);

            var xhr =new XMLHttpRequest();
            xhr.open('POST', url);
            xhr.setRequestHeader('Content-Type','application/json');
            xhr.send(data);

            xhr.addEventListener('load', function(){
                console.log(xhr.responseText);
                var result=JSON.parse(xhr.responseText);
                console.log("result  :",result);
                if(result.result!=="ok")return;
                document.querySelector(".result").innerHTML=result.email;
            });
        }
*/        
        function sendAjax(url, data){
            fetch(url, {
                headers:{'Content-Type' :"application/json"},
                method:"POST",
                body:JSON.stringify({'email':data})
            }) .then(res=>res.json())  
            .then(res=>{
                console.log(" res :  ", res);

                const resultDiv=document.querySelector(".result");

                if(res.result!=="ok")return resultDiv.innerHTML="your email is not found";
                else resultDiv.innerHTML=res.name;
            }).catch(err=>console.error("에러:",err));
        }
    </script>
</body>
</html>

 

 

 

 

 

 

 

4. Router 개선 - 모듈화

 

 

10) Routing 모듈화

 

 

강의 :   https://www.inflearn.com/course/node-js-%EC%9B%B9%EA%B0%9C%EB%B0%9C/unit/6132?tab=curriculum

 

app.js

~

const mainRouter = require("./router/main");



~

app.use("/main", mainRouter);

 

 

router/main.js

const express = require("express");
const router = express.Router();
const path = require('path');


router.get("/", function (req, res) {
    console.log(" main js loaded    ");
    res.sendFile(path.join(__dirname, "../public/main.html"));
});


module.exports = router;

 

 

 

 

 

 

11 )Routing 모듈화 2 (DB연결부분)

 

강의 :  https://www.inflearn.com/course/node-js-%EC%9B%B9%EA%B0%9C%EB%B0%9C/unit/6133?tab=curriculum

 

 

app.js

const express = require('express');
const app = express();


const mainRouter = require("./router/main");
const emailRouter = require("./router/email");


//static 파일 등록 처리
app.use(express.static("public"));

//app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.set('view engine', 'ejs');


app.use("/main", mainRouter);
app.use("/email", emailRouter);


app.get("/", function (req, res) {
    console.log("test");
    //res.send("<h1>h1 friend</h1>");
    res.sendFile(__dirname + "/public/main.html");
});


app.listen(3000, function () {
    console.log("start! express server on port 3000");
});

 

router/email.js

const express = require('express');
const router = express.Router();
const mysql = require('mysql');
const db = mysql.createConnection({
    host: 'localhost',
    user: 'node_inflearn',
    password: '1111',
    database: 'node_inflearn'
});
db.connect();


router.post("/form", function (req, res) {
    console.log("req.body : ", req.body.email);
    //res.send(`<h1>welcome! ${req.body.email}</h1>`);
    res.render('email.ejs', { 'email': req.body.email })
});

router.post("/ajax", function (req, res) {
    console.log("ajax email - req.body : ", req.body.email);
    //check validation about input value => select db

    db.query("select name from users where email =?", [req.body.email], function (err, rows) {
        if (err) return res.status(400).json({ err: err });
        if (rows[0]) return res.status(200).json({ result: "ok", name: rows[0].name })
        else return res.status(200).json({ result: "none", name: "" })
    });
});

module.exports = router;

 

public/form.html

<!DOCTYPE html>
<html lang="en">
<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>email form</title>
</head>
<body>
    <form action="/email/form" method="post">
        email :  <input type="text" name="email"><br/>
        submit : <input type="submit">
    </form>
    
    <button class="ajaxsend">ajaxsend</button>

    <div class="result"></div>
    <script>
        document.querySelector('.ajaxsend').addEventListener('click',function(){
            var inputdata =document.forms[0].elements[0].value;
            sendAjax('/email/ajax',inputdata);
        });
       
        function sendAjax(url, data){
            fetch(url, {
                headers:{'Content-Type' :"application/json"},
                method:"POST",
                body:JSON.stringify({'email':data})
            }) .then(res=>res.json())  
            .then(res=>{
                console.log(" res :  ", res);

                const resultDiv=document.querySelector(".result");

                if(res.result!=="ok")return resultDiv.innerHTML="your email is not found";
                else resultDiv.innerHTML=res.name;
            }).catch(err=>console.error("에러:",err));
        }
    </script>
</body>
</html>

 

 

 

 

 

12) Routing 리팩토링

 

강의 :   https://www.inflearn.com/course/node-js-%EC%9B%B9%EA%B0%9C%EB%B0%9C/unit/6134?tab=curriculum

 

 

app.js

const express = require('express');
const app = express();
const router = require("./router");


app.use(express.static("public")); //static 파일 등록 처리
//app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.set('view engine', 'ejs');

app.use(router);

app.listen(3000, function () {
    console.log("start! express server on port 3000");
});

 

router/main.js  ->  router/main/main.js 

router/email.js  ->  router/main/email.js 

 

router/index.js

const express = require('express');
const router = express.Router();
const path = require('path');
const mainRouter = require("./main/main");
const emailRouter = require("./email/email");


router.get("/", function (req, res) {
    console.log("index");
    res.sendFile(path.join(__dirname, "../public/main.html"));
});

router.use("/main", mainRouter);
router.use("/email", emailRouter);

module.exports = router;

 

 

 

 

 

 

5. DB에 데이터추가

 

 

 

13) DB에 데이터추가 (create user) 1편

 

강의 :   https://www.inflearn.com/course/node-js-%EC%9B%B9%EA%B0%9C%EB%B0%9C/unit/6136?tab=curriculum

 

router/index.js

const express = require('express');
const router = express.Router();
const path = require('path');
const mainRouter = require("./main/main");
const emailRouter = require("./email/email");
const joinRouter = require("./join/join");

router.get("/", function (req, res) {
    console.log("index");
    res.sendFile(path.join(__dirname, "../public/main.html"));
});

router.use("/main", mainRouter);
router.use("/email", emailRouter);
router.use("/join", joinRouter);

module.exports = router;


 

router/join/join.js

const express = require('express');
const router = express.Router();
const path = require("path");
const db = require("../../lib/db");


router.get("/", function (req, res) {
    console.log("join page  ...");
    res.sendFile(path.join(__dirname, "../../public/join.html"));
});


module.exports = router;

 

 

public/join.html

<!DOCTYPE html>
<html lang="en">
<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>Join</title>
</head>
<body>
    <h1>Join my website!</h1>
    <form action="/join" method="post">
        email :  <input type="text" name="email"><br/>
        name :  <input type="text" name="name"><br/>
        password :  <input type="password" name="password"><br/>
        <input type="submit">
    </form>
   
</body>
</html>

 

 

 

 

 

 

14) DB에 데이터추가 (create user) 2편

 

강의 :   https://www.inflearn.com/course/node-js-%EC%9B%B9%EA%B0%9C%EB%B0%9C/unit/6137?tab=curriculum

 

 

lib/db.js

const mysql = require('mysql');
const db = mysql.createConnection({
    host: 'localhost',
    user: 'node_inflearn',
    password: '1111',
    database: 'node_inflearn'
});
db.connect();

module.exports = db;

 

 

router/join/join.js

const express = require('express');
const router = express.Router();
const path = require("path");
const db = require("../../lib/db");


router.get("/", function (req, res) {
    console.log("join page  ...");
    res.sendFile(path.join(__dirname, "../../public/join.html"));
});


router.post("/", function (req, res) {
    const name = req.body.name;
    const email = req.body.email;
    const password = req.body.password;

    db.query("INSERT INTO users(name, email, password) VALUES (?, ? ,? )", [name, email, password], function (err, rows) {
        if (err) { throw err; }
        console.log("ok db insert");
        res.json("ok");
    });

});


module.exports = router;

 

 

 

 

 

 

 

 

15) DB에 데이터추가 (create user) 3편

 

강의 :   https://www.inflearn.com/course/node-js-%EC%9B%B9%EA%B0%9C%EB%B0%9C/unit/6138?tab=curriculum

 

public/join.html

<!DOCTYPE html>
<html lang="en">
<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>Join</title>
</head>
<body>
    <h1>Join my website!</h1>
    <form action="/join" method="post">
        email :  <input type="text" name="email"><br/>
        name :  <input type="text" name="name"><br/>
        password :  <input type="password" name="password"><br/>
        <input type="submit">
    </form>   
</body>
</html>

 

 

router/join/join.js

const express = require('express');
const router = express.Router();
const path = require("path");
const db = require("../../lib/db");


router.get("/", function (req, res) {
    console.log("join page  ...");
    res.sendFile(path.join(__dirname, "../../public/join.html"));
});


router.post("/", function (req, res) {
    const name = req.body.name;
    const email = req.body.email;
    const password = req.body.password;

    db.query("INSERT INTO users(name, email, password) VALUES (?, ? ,? )", [name, email, password], function (err, rows) {
        if (err) throw err;
        else res.render("welcome.ejs", { id: rows.insertId, name: name });
    });

});


module.exports = router;

 

 

views/welcome.ejs

<!DOCTYPE html>
<html lang="kor">
<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>Welcome</title>
</head>
<body>    
    <h1>Welcome !! <%= name %></h1>
    <p><%= id %> 번째 가입자 이시네요~ !! 축하드려요</p>    
</body>
</html>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

nodejs

 

about author

PHRASE

Level 60  라이트

실물의 형상이 굽으면 그 그림자도 또한 굽다. 좋은 결과를 얻기를 바란다면 좋은 행위를 해야 한다. -관자

댓글 ( 4)

댓글 남기기

작성