ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Node.js] 5. http 모듈 - Node.js 강좌
    Web/Node.js 2015. 6. 12. 16:39
    Chapter 5. http 모듈

     Node.js에서 가장 기본적인 웹 모듈이며 HTTP 웹 서버를 생성하는 것과 관련된 모든 기능을 담당합니다.



    1. server 객체

     http 모듈에서 가장 중요한 객체는 server 객체입니다. http 모듈의 createServer() 메서드를 사용하여 server 객체를 생성 가능 합니다.


     Server 객체의 메서드

     - listen(port[, callback]) : 서버를 실행합니다.

     - close() : 서버를 종료합니다.


     Server 객체의 이벤트

     - request : 클라이언트가 요청할 때 발생하는 이벤트입니다.

     - connection : 클라이언트가 접속할 때 발생하는 이벤트입니다.

     - close : 서버가 종료될 때 발생하는 이벤트입니다.

     - checkContinue : 클라이언트가 지속적인 연결을 하고 있을 때 발생하는 이벤트입니다.

     - upgrade : 클라이언트가 HTTP 업그레이드를 요청할 때 발생하는 이벤트입니다.

     - clientError : 클라이언트에서 오류가 발생할 때 발생하는 이벤트입니다.


     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    var http = require('http');
     
    var server = http.createServer();
     
    server.on('request'function() {
        console.log('Request on');
    });
     
    server.on('connection'function() {
        console.log('Connection on');
    });
     
    server.on('close'function() {
        console.log('Close on');
    });
     
    server.listen(52273);
    cs










    2. response 객체

     간단한 응답 메시지 작성 예제를 통해 response 객체를 알아봅시다.

     

     response 객체의 메서드

     - writeHead(statusCode, object) : 응답 헤더를 작성합니다.

     - end([data], [encoding]) : 응답 본문을 작성합니다.



     

    1
    2
    3
    4
    5
    6
    7
    // 웹서버 생성 및 실행
    require('http').createServer(function (request, response) {
        response.writeHead(200, {'Content-Type''text/html' });
        response.end('<h1>Hello Web Server with Node.js !!! </h1>');
    }).listen(52273function() {
        console.log('52273 port is using...');
    });
    cs

















    2-1. File System 모듈을 사용한 HTML 페이지 제공

     자바스크립트 파일 위에서 모든 HTML 페이지를 문자열로 작성하는 것은 불가능합니다. 

     이번 절에서 File System 모듈을 사용하여 서버에 존재하는 HTML 페이지를 클라이언트에게 제공합니다.



     먼저 서버를 작성합니다.


     server.js


     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
     
     
    //모듈 추출
    var fs = require('fs');
     
    var http = require('http');
     
    http.createServer(function (request, response) {
        // HTML File Read
        fs.readFile('HTMLPage.html'function(error, data) {
            response.writeHead(200, {'Content-Type''text/html'});
            response.end(data);
        });
        
    }).listen(52273function() {
        console.log('Server running at http://127.0.0.1:52273');
    });
     
    cs

     


     다음 HTMLPage.html을 작성합니다.


     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <!DOCTYPE html>
    <html>
        <head>
            <title>Index</title>
        </head>
        <body>
            <h1>Hello Node.js</h1>
        </body>
    </html>
     
    cs








    2-2. 이미지와 음악 파일 제공

     이번 절에서는 이미지와 음악을 같은 경로 내에 넣어주세요


     server.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
     
    //모듈 추출
    var fs = require('fs');
    var http = require('http');
     
    http.createServer(function (request, response) {
        // Image File Read
        fs.readFile('eva.jpeg'function(error, data) {
            response.writeHead(200, {'Content-Type''image/jpeg'});
            response.end(data);
        });
        
    }).listen(52273function() {
        console.log('Server running at http://127.0.0.1:52273');
     
    });
     
     
    http.createServer(function (request, response) {
        // Music File Read
        fs.readFile('Sam Smith.mp3'function(error, data) {
            response.writeHead(200, {'Content-Type''audio/mp3'});
            response.end(data);
        });
        
    }).listen(52274function() {
        console.log('Server running at http://127.0.0.1:52274');
    });
    cs

     










     

     


     MIME 형식

     - text/plain

     - text/html

     - text/css

     - text/xml

     - image/jpeg

     - image/png

     - video/mpeg

     - audio/mp3









    2.3 쿠키 생성

     쿠키는 키와 값이 들어 있는 작은 데이터 조각으로, 이름, 값, 파기 날짜와 경로 정보를 가지고 있습니다. 

     쿠키는 서버와 클라이언트에서 모두 저장하고 사용할 수 있습니다. 쿠키는 일정 기간 동안 데이터를 저장할 수 있으므로 일정 기간 동안 로그인을 유지하는 데 사용됩니다.


     response 객체를 사용하면 클라이언트에게 쿠키를 할당할 수 있습니다. 

     쿠키를 할당할 때 응답 헤더의 Set-Cookie 속성을 사용합니다. Set-Cookie 속성에는 쿠키의 배열을 넣습니다.


     ex)

      Name = Value; Expires = Date; Domain = domain; Path = path; Secure




     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    var http = require('http');
     
    http.createServer(function (request, response) {
        var date = new Date();
        date.setDate(date.getDate() + 7);
        
        response.writeHead(200, {
            'Content-Type''text/html',
            'Set-Cookie': [
                'breakfast = toast; Expires = ' + date.toUTCString(),
                'dinner = chicken'
            ]
        });
        
        response.end('<h1>' + request.headers.cookie + ' </h1>');
    }).listen(52273function () {
        console.log('Server running at http://127.0.0.1:52273');
    });
    cs












    2.4 페이지 강제 이동

     


     

    1
    2
    3
    4
    5
    6
    7
    8
    var http = require('http');
     
    http.createServer(function (request, response) {
        response.writeHead(302, { 'Location''http://www.naver.com'});
        response.end();
    }).listen(52273function() {
        console.log('Server running at http://127.0.0.1:52273');
    });
    cs







     





    3. request 객체

     Server 객체의 request 이벤트가 발생할 때 이벤트 핸들러의 첫 번째 매개 변수에 request 객체가 들어갑니다.


     request 객체의 속성

     - method : 클라이언트 요청 방식을 나타냅니다.

     - url : 클라이언트가 요청한 URL을 나타냅니다.

     - headers : 요청 메시지 헤더를 나타냅니다.

     - trailers : 요청 메시지 트레일러를 나타냅니다.

     - httpVersion : HTTP 프로토콜 버전을 나타냅니다.


    3.1 url 속성을사용한 페이지 구분

     요청 메시지의 URL에 따라 서로 다른 웹 페이지를 제공하는 예제를 만들어봅시다.

     - app.js

     - Index.html

     - OtherPage.html


     Index.html

     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    <!DOCTYPE html>
    <html>
        <head>
            <title>Index</title>
        </head>
        <body>
            <h1>Hello Node.js - Index Page</h1>
        </body>
    </html>
    cs



     OtherPage.html

     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    <!DOCTYPE html>
    <html>
        <head>
            <title>OtherPage</title>
        </head>
        <body>
            <h1>Hello Node.js - OtherPage Page</h1>
        </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
    var http = require('http');
    var fs = require('fs');
    var url = require('url');
     
    http.createServer( function (request, response) {
        var pathName = url.parse(request.url).pathname;
        
        if (pathName == '/') {
            fs.readFile('Index.html'function(error, data) {
                response.writeHead(200, {'Content-Type''text/html'});
                response.end(data);
            });
        } else if (pathName == '/OtherPage') {
            fs.readFile('OtherPage.html'function(error, data) {
                response.writeHead(200, {'Content-Type''text/html'});
                response.end(data);
            });
        }
    }).listen(52273function() {
        console.log('Server running at http://127.0.0.1:52273');
    });
    cs



    Index.html 접근시





    OtherPage.html 접근시


     



    3.2 method 속성을 사용한 페이지 구분

     request 객체의 method 속성을 이용하여 요청 방식에 따라 페이지를 쉽게 구분할 수 있습니다.


     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    var http = require('http');
     
    http.createServer(function (request, response) {
        if (request.method == 'GET') {
            console.log('GET request');
        } else if(request.method == 'POST') {
            console.log('POST request');
        }
    }).listen(52273function() {
        console.log('Server running at http://127.0.0.1:52273');
    });
    cs




     




    3. 3 GET & POST 요청 매개 변수 추출

     GET 요청과 POST 요청에서 매개 변수를 처리하는 방법을 살펴보겠습니다.


     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    var http = require('http');
    var url = require('url');
     
    http.createServer(function (request, response) {
        var query = url.parse(request.url, true).query;
        
        response.writeHead(200, {'Content-Type''text/html'});
        response.end('<h1>' + JSON.stringify(query) + '</h1>');
    }).listen(52273function() {
        console.log('Server running at http://127.0.0.1:52273');
    });
    cs


     위와 같이 작성하고 http://127.0.0.1:52273?name=Yeonsu&region=Seoul 로 접속합니다.




     






    다음은 POST 방식인데, GET 방식보다 데이터를 더 많이 담을 수 있고 보안 측면에서도 좋습니다.



    HTMLPage.html

     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    <!DOCTYPE html>
    <html>
        <head>
            <title>Node.js Example</title>
        </head>
        <body>
            <h1>Send Data With POST Method</h1>
            <form method="POST">
                <table>
                    <tr>
                        <td><label>Data A</label></td>
                        <td><input type="text" name="data_a"/></td>
                    </tr>
                        <td><label>Data B</label></td>
                        <td><input type="text" name="data_b"/></td>
                </table>
                <input type="submit"/>
            </form>
        </body>
    </html>
    cs




     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    var http = require('http');
    var fs = require('fs');
     
    http.createServer(function (request, response) {
        if (request.method == 'GET') {
            fs.readFile('HTMLPage.html'function (error, data) {
                response.writeHead(200, {'Content-Type''text/html'});
                response.end(data);
            });
        } else if (request.method == 'POST') {
            request.on('data'function(data) {
                response.writeHead(200, {'Content-Type''text/html'});
                response.end('<h1>' + data + '</h1>');
            });
        }
    }).listen(52273function() {
        console.log('Server running at http://127.0.0.1:52273');
    });
    cs








     





    3. 4 쿠키 추출

     response 객체를 다루면서 쿠키를 생성하는 방법을 배웠습니다.

     이 절에서는 request 객체를 사용하여 쿠키를 추출하는 방법을 배워보겠습니다.


     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    var http = require('http');
     
    http.createServer(function (request, response) {
        var cookie = request.headers.cookie;
        cookie = cookie.split(';').map(function (element) {
            var element = element.split('=');
            return {
                key: element[0],
                value: element[1]
            };
        });
        
        response.writeHead(200, {
            'Content-Type''text/html',
            'Set-Cookie': ['name = Yeonsu''region = Seoul']
        });
        
        response.end('<h1>' + JSON.stringify(cookie) + '</h1>');
    }).listen(52273function() {
        console.log('Server running at http://127.0.0.1:52273');
    });
    cs

     




     



    node 강좌, nodejs 강좌, node.js


     

     



     

    이 포스팅은 '모던 웹을 위한 Node.js 프로그래밍'을 참고로 작성하였습니다.


    댓글

Designed by Tistory.