Node.js & express 설치 및 구현


목차

  1. Express 설치
  2. Express 실습
  3. Express 실습 결과


Express 설치 ▲top


Express란?

    • Node.js 의 웹 애플리케이션 프레임워크
    • 라우팅작업을 할 때 편리하다.
    • 공식 사이트 : http://expressjs.com/ko/
라우팅이란?
Express 설치
package.json 에 express 를 수록한다.

C:\Users\...\nodejs> npm install express --save


Express 실습 ▲top

  • 실습 프로젝트 파일구조
    ./node_modules    (폴더)
    ./models               (폴더)
        board.js
        reply.js
    ./routes                (폴더)
        board.js
        reply.js
    package.json
    app.js
  1. app.js 
    node명령어를 이용해서 맨 처음 실행할 js파일.
    express를 이용하여 웹서버를 구현한다.
    express를 이용한 라우팅작업을 전문으로 하는 파일을 정의한다.


  2. ./routes/board.js
    app.js에서 정했듯이 클라이언트에서 /board 로 시작하는 주소를 입력하면  /board 주소 이후의 주소에 대한 라우팅작업을 담당하게 된다.

  3. ./routes/reply.js
    클라이언트에서 /reply 로 시작하는 주소를 입력하면  /reply 주소 이후의 주소에 대한 라우팅작업을 담당하게 된다.

  4. ./models/board.js
    ./routes/board.js에서 지시하는 작업만을 처리하려고 마련된 작업처리공간.

  5. ./models/reply.js
    ./routes/reply.js에서 지시하는 작업만을 처리하려고 마련된 작업처리공간.


  • 실습 프로젝트 코드
    • 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
      'use strict';
       

      const express = require('express');
      const app = express();
      const bodyParser = require('body-parser');
       
      // CORS : Cross Origin Resource Sharing
      // 보안 상의 이유로, 브라우저들은 스크립트 내에서 초기화되는 cross-origin HTTP 요청을 제한하는데, 이를 수정하는 로직.
      app.use(function(req, res, next) {
          res.header("Access-Control-Allow-Origin""*");
          res.header("Access-Control-Allow-Headers"'Content-Type, Authorization, Content-Length, X-Requested-With');
          res.header("Access-Control-Allow-Methods""PUT, POST, GET, OPTIONS, DELETE");
          next();
      });
       
      // Body-Parser 추가 : 터미널설치 - npm i body-parser --save
      app.use(bodyParser.json());
      app.use(bodyParser.urlencoded({extended: true}));
       
      // Connect to Web Server
      var port = '8000';
      app.listen(port, ()=>{
          console.log('[Express] Smartbed web Server started at %d port', port);
      });
       
      // 사용자 정의 Middleware 추가. 이처럼 라우팅 모듈 설정 시에는 파라미터를 두개 사용
      // 첫번째 파라미터의 주소에 대해서는 두번째 파라미터로 오는 미들웨어가 담당하도록 한다
      app.use('/board', require('./routes/board'));  // 1. 게시판
      app.use('/reply', require('./routes/reply'));  // 2. 댓글
       
      app.get('/', (req, res) => {
          fs.readFile('./main.html''utf8'function(err, data) {
              // writeHead: 응답 헤더를 작성합니다.
              // 200: 응답 성공, text/html: html문서
              res.writeHead(200, {'Content-Type''text/html'});
              // end: 응답 본문을 작성합니다.
              res.end(data);
          });
      });
      cs

    • main.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
      <!DOCTYPE html>
      <html lang="">
      <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title></title>
      </head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <body>
          <button id="getboard">board/get</button>
          <button id="postboard">board/post</button>
          <button id="putboard">board/put</button>
          <button id="deleteboard">board/delete</button>
          <button id="getreply">reply/get</button>
          <button id="postreply">reply/post</button>
          <button id="putreply">reply/put</button>
          <button id="deletereply">reply/delete</button>
          <script>
              /* Ajax connection */
              function connectToServer(url, method){
                  $.ajax({ 
                      url: url,
                      method: method,
                      contentType: 'application/json',
                      dataType : "JSON",
                      crossDomain: true,
                      success: function(result) {
                          console.log('결과', result);
                      },
                      error:function(xhr,status,error){
                      }
                  });    
              }
              $('#getboard').on('click', (e)=>{connectToServer('http://127.0.0.1:8000/board/read''get')})
              $('#postboard').on('click', (e)=>{connectToServer('http://127.0.0.1:8000/board/write''post')})
              $('#putboard').on('click', (e)=>{connectToServer('http://127.0.0.1:8000/board/modify''put')})
              $('#deleteboard').on('click', (e)=>{connectToServer('http://127.0.0.1:8000/board/delete''delete')})
              $('#getreply').on('click', (e)=>{connectToServer('http://127.0.0.1:8000/reply/read''get')})
              $('#postreply').on('click', (e)=>{connectToServer('http://127.0.0.1:8000/reply/write''post')})
              $('#putreply').on('click', (e)=>{connectToServer('http://127.0.0.1:8000/reply/modify''put')})
              $('#deletereply').on('click', (e)=>{connectToServer('http://127.0.0.1:8000/reply/delete''delete')})
          </script>
      </body>
      </html>
      cs

    • ./routes/board.js
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      // board.js
      'use strict';
       
      const express = require('express');
      const router = express.Router();
      const boardController = require('../models/board');
       
      /** 글보기 **/
      router.get('/read', boardController.read);
       
      /** 글쓰기 **/
      router.post('/write', boardController.write);
       
      /** 글수정 **/
      router.put('/modify', boardController.modify);
       
      /** 글제거 **/
      router.delete('/delete', boardController.delete);
       
      module.exports = router;
      cs

    • ./routes/reply.js
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      // reply.js
      'use strict';
       
      const express = require('express');
      const router = express.Router();
      const replyController = require('../models/reply');
       
      /** 댓글보기 **/
      router.get('/read', replyController.read);
       
      /** 댓글쓰기 **/
      router.post('/write', replyController.write);
       
      /** 댓글수정 **/
      router.put('/modify', replyController.modify);
       
      /** 댓글제거 **/
      router.delete('/delete', replyController.delete);
       
      module.exports = router;
      cs

    • ./models/board.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
      // board.js
      'use strict';
       
      /** 글보기 **/
      exports.read = function(req, res){
          console.log('read');
          res.send({'result':'read'});
      }
       
      /** 글쓰기 **/
      exports.write = function(req, res){
          console.log('write');
          res.send({'result':'write'});
      }
       
      /** 글수정 **/
      exports.modify = function(req, res){
          console.log('modify');
          res.send({'result':'modify'});
      }
       
      /** 글제거 **/
      exports.delete = function(req, res){
          console.log('delete');
          res.send({'result':'delete'});
      }
       
      /** (내부용) **/
      var innerFunction = function(param){    
          console.log('innerFunction param :',param);
      }
      exports.innerFunction = innerFunction;
      cs

    • ./models/reply.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
      // reply.js
      'use strict';
       
      const board = require('./board');
      // board.js의 require을 쓰고싶다면,
      // board.js내부에서 exports로 내보낸 function에 한해서만 require해 와서 사용이 가능하다.
       
      /** 글보기 **/
      exports.read = function(req, res){
          console.log('reply read');
          res.send({'result':'reply read'});
      }
       
      /** 글쓰기 **/
      exports.write = function(req, res){
          console.log('reply write');
          res.send({'result':'reply write'});
      }
       
      /** 글수정 **/
      exports.modify = function(req, res){
          console.log('reply modify');
          res.send({'result':'reply modify'});
      }
       
      /** 글제거 **/
      exports.delete = function(req, res){
          console.log('reply delete');
          innerReply('innerReply!!');
          board.innerFunction('hi from reply');
          res.send({'result':'reply delete'});
      }
       
      /** (내부용) **/
      var innerReply = function(param){    
          console.log('reply innerFunction param :',param);
      }
      exports.innerFunction = innerReply;
      cs


Express 실습 결과▲top


 클라이언트 요청

 서버 로그

 클라이언트 결과 리턴

 board/get

 read

 {result : read}

 board/post

 write

 {result : write}

 board/put

 modify

 {result : modfy}

 board/delete

 delete

 {result : delete}

 reply/get

 reply read

 {result : reply read}

 reply/post

 reply write

 {result : reply write}

 reply/put

 reply modify

 {result : reply modfy}

 reply/delete

 reply delete

 reply innerFunction param : innerReply!!

 innerFunction param : hi from reply

 {result : reply delete}



+ Recent posts