본문 바로가기

Node.js

Node.js http 모듈



  • http 모듈은 Node.js의 가장 기본적인 웹 모듈이며 HTTP 웹 서버와 클라이언트를 생성하는 것과 관련된 모든 기능을 담당한다.


1. 요청과 응답

  • 일반적으로 많이 알고 있는 요청과 응답에 대한 내용이다.
  • 요청은 클라이언트가 서버로부터 요구하는 것을 말한다.
  • 응답은 서버가 클라이언트로부터 받은 요청에 대한 정보를 제공해주는 것을 말한다.
  • 기초적인 내용이라 내용 생략.

2. server 객체
  • http 모듈에서 가장 중요한 객체는 server 객체이다.
  • http 모듈의 createServer() 메서드를 사용하면 server 객체를 생성할 수 있다.
[ 코드 - 웹 서버 생성과 실행 ]
//모듈을 실행한다.
var http = require('http');

//웹 서버를 생성한다.
var server = http.createServer();

//웹 서버를 실행한다.
server.listen(52273);
  • 서버 객체를 생성하고 52273번 포트를 사용하여 서버를 실행한다.

[ 메서드 - server 객체의 메서드 ]
  • listen(port[, callback]) : 서버를 실행한다.
  • close() : 서버를 종료한다.

[코드 - server 객체의 close() 메서드 ]
//서버를 생성한다.
var server = require('http').createServer();

//서버를 실행한다.
server.listen(52273, function () {
console.log('Server Running at http://127.0.0.1:52273');
});

//10초 후 함수를 실행한다.
setInterval(function () {
//서버를 종료한다.
server.close();
}, 10000);
  • 서버를 실행하여 10초 후 서버를 종료한다.
[ 이벤트 - server 객체의 이벤트 ]
  • request : 클라이언트가 요청할 때 발생하는 이벤트이다.
  • connection : 클라이언트가 접속할 때 발생하는 이벤트이다.
  • close : 서버가 종료될 때 발생하는 이벤트이다.
  • checkContinue : 클라이언트가 지속적인 연결을 하고 있을 때 발생하는 이벤트이다.
  • upgrade : 클라이언트가 HTTP 업그레이드를 요청할 때 발생하는 이벤트이다.
  • clientError : 클라이언트에서 오류가 발생할 때 발생하는 이벤트이다.


[ 코드 - server 객체의 이벤트 ]

//모듈을 추출한다.

var http = require('http');


//server 객체를 생성한다.

var server = http.createServer();


//server 객체에 이벤트를 연결한다.

server.on('request', function() {

console.log('Request On');

});

server.on('connection', function() {

console.log('Connection On');

});

server.on('close', function() {

console.log('Close On');

});


//listen() 메서드를 실행한다.

server.listen(52273);

  • 코드를 실행한 후 웹 브라우저를 사용하여 http://127.0.0.1:52273에 접속한다.
  • 웹 브라우저는 요청했지만 응답이 없으므로 아무것도 출력되지 않을 것이다.
  • 하지만 콘솔 화면을 살펴보면 이벤트가 실행된 것을 확인할 수 있다.
[ 실행 - server 객체의 이벤트 ]


3. response 객체
  • 클라이언트에 웹 페이지를 제공하려면 응답 메시지를 작성해야 한다.
  • 응답 메시지를 작성할 때는 response 객체를 사용한다.
  • response 객체는 request 이벤트 리스너의 두 번째 매개변수로 전달되는 객체이다.

[ 메서드 - response 객체의 메서드 ]
  • writeHead(statusCode, object) : 응답 헤더를 작성한다.
  • end([data], [encoding]) : 응답 본문을 작성한다.

[ 코드 - 간단한 응답 메시지 작성 ]
//웹 서버를 생성하고 실행한다.
require('http').createServer(function (request, response) {
//응답한다.
response.writeHead(200, {'Content-Type': 'text/html'});
response.end('<h1>Hello Web Server with Node.js</h1>');
}).listen(52273, function () {
console.log('Server Running at http://127.0.0.1:52273');
});
  • 코드를 실행한 후 웹 브라우저에서 http://127.0.0.1:52273에 접속한다.

[ 실행 - 간단한 응답 메시지 작성 ]


3.1 File System 모듈을 사용한 HTML 페이지 제공

  • 자바스크립트 파일 위에서 모든 HTML 페이지를 문자열로 작성하는 것은 불가능하다.
  • File System 모듈을 사용하여 서버에 존재하는 HTML 페이지를 클라이언트에 제공한다.

[ 코드 - 서버 생성 및 실행 ]
//모듈을 추출한다.
var fs = require('fs');
var http = require('http');

//웹 서버를 생성하고 실행한다.
http.createServer(function (request, response) {

}).listen(52273, function () {
console.log('Server Running at http://127.0.0.1:52237');
});

[ 코드 - HTML 파일 제공 ]
//모듈을 추출한다.
var fs = require('fs');
var http = require('http');

//웹 서버를 생성하고 실행한다.
http.createServer(function (request, response) {
//HTML 파일을 읽는다.
fs.readFile('HTMLPage.html', function (error, data) {
response.writeHead(200, {'Content-type' : 'text/html'} );
response.end(data);
});
}).listen(52273, function () {
console.log('Server Running at http://127.0.0.1:52273');
});


[ 코드 - HTMLPage.html ]

<!DOCTYPE html>

<html>

<head>

<title>Index</title>

</head>

<body>

<h1>Hello Node.js</h1>

<h2>Test page</h2>

<p>Lorem ipsum dolor sit amet.</p>

</body>

</html>


[ 실행 - HTML 제공 파일 ]

  • HTMLPage.html 파일의 HTML 페이지를 볼 수 있다.

3.2 이미지와 음악 파일 제공

  • 파일을 제공하는 웹 서버를 만들어보겠다.
  • JPG 이미지 파일과 MP3 음악 파일을 준비한다.

[ 코드 - 서버 생성 및 실행 ]

//모듈을 추출한다.

var fs = require('fs');

var http = require('http');


//52273번 포트에 서브를 생성하고 실행한다.

http.createServer(function (request, response) {


}).listen(52273, function () {

console.log('Server Running at http://127.0.0.1:52273');

});


//52274번 포트에 서버를 생성하고 실행한다.

http.createServer(function (request, response) {


}).listen(52274, function() {

console.log('Server Running at http://127.0.0.1:52274');

});

  • 포트 2개를 사용하여 서버를 2개 생성한다.


[ 코드 - 52273번 포트의 이미지 파일 제공 ]

//52273번 포트에 서브를 생성하고 실행한다.

http.createServer(function (request, response) {

//이미지 파일을 읽는다.

fs.readFile('crystalrain.jpg', function (error, data) {

response.writeHead(200, { 'Content-Type' : 'image/jpeg' });

response.end(data);

});

}).listen(52273, function () {

console.log('Server Running at http://127.0.0.1:52273');

});

  • 특정 형식 파일을 제공할 때 가장 중요한 것은 응답 헤더의 Content-Type 속성이다.
  • Content-Type 속성은 MIME 형식을 입력한다. (image/jpeg)
[ 코드 - 52274번 포트의 음악 파일 제공 ]
//52274번 포트에 서버를 생성하고 실행한다.
http.createServer(function (request, response) {
//음악 파일을 읽는다.
fs.readFile('06 Brunch.mp3', function (error, data) {
response.writeHead(200, { 'Content-Type' : 'audio/mp3' });
response.end(data);
});
}).listen(52274, function() {
console.log('Server Running at http://127.0.0.1:52274');
});
  • 응답 헤더의 Content-Type 속성을 'audio/mp3'로 입력한다.
[ 실행 - 서버 실행 ]


[ 실행 - 이미지 파일 제공 ]



[ 실행 - 음악 파일 제공 ]


[ MME 형식의 예 ]

  • text/plain : 기본적인 텍스트
  • text/html : HTML 문서
  • text/css : CSS 문서
  • text/xml : XML 문서
  • image/jpeg : JPG/JPEG 그림 파일
  • image/png : PNG 그림 파일
  • video/mpeg : MPEG 비디오 파일
  • audio/mp3 : MP3 음악 파일

※ 그 외에도 굉장히 많다.


3.3 쿠키 생성

  • 쿠키는 키(key)와 값(value)이 들어 있는 작은 데이터 조각으로 이름, 값, 파기 날짜와 경로 정보를 가지고 있다.
  • 쿠키는 서버와 클라이언트에서 모두 저장하고 사용할 수 있다.
  • 쿠키는 일정 기간 동안 데이터를 저장할 수 있으므로 일정 기간 동안 로그인을 유지하는 웹사이트에 사용한다.
  • response 객체를 사용하면 클라이언트에 쿠키를 할당할 수 있다.
  • 쿠키를 할당할 때는 응답 헤더의 Set-Cookie 속성을 사용한다.
  • Set-Cookie 속성에는 쿠키의 배열을 넣는다.

[ 쿠키의 형태 ]
Name = Value; Expires = 날짜; Domain = 도메인; Path = 경로; Secure

[ 코드 - 쿠키 저장 및 출력 ]
//모듈을 추출한다.
var http = require('http');

//서버를 생성하고 실행한다.
http.createServer(function (request, response) {
//쿠키를 입력한다.
response.writeHead(200, {
'Content-Type' : 'text/html',
'Set-Cookie' : [
'breakfast = toast; Expires = ' + date.toUTCString(),
'dinner = chicken'
]
});

//쿠키를 출력한다.
response.end('<h1>' + request.headers.cookie + '</h1>');
}).listen(52273, function() {
console.log('Server Running at http://127.0.0.1:52273');
});


[ 실행 - 쿠키 저장 및 출력 (1번째 실행) ]

  • 처음 요청을 할 때는 클라이언트가 쿠키를 갖고 있지 않으므로 undefined로 표시된다. (이미 생성되어 있는 쿠키에 대해서만 쿠키 정보를 불러올 수 있다.)
  • 하지만 쿠키 생성이 실행되었으므로 다음에 요청할 때에는 쿠키 정보를 불러올 수 있다.


[ 실행 - 쿠키 저장 및 출력 (2번째 실행) ]

  • 1번째 요청했을 때 쿠키 생성을 했으므로 2번째 요청했을 때에는 쿠키 정보를 불러올 수 있다.


3.4 페이지 강제 이동

[ 코드 - Location 속성을 사용한 페이지 강제 이동 ]

//모듈을 추출한다.

var http = require('http');


//웹 서버를 생성 및 실행한다.

http.createServer(function (request, response) {

    response.writeHead(302, {'Location' : 'http://m.naver.com'});

    response.end();

}).listen(52273, function() {

    console.log('Server Running at http://127.0.0.1:52273');

});


[ 실행 - Location 속성을 사용한 페이지 강제 이동 ]

  • http://127.0.0.1:52273 으로 접속하면 m.naver.com 으로 페이지 강제 이동을 한다.

[ HTTP Status Code 예 ]
  • writeHead() 메서드의 첫 번째 매개변수를 Status Code라 부른다.
  • 위 예제에서 사용된 302는 강제 페이지 이동을 구현할 때 가장 많이 사용된다.
  • 1XX : 처리 중
    ex) 100 Continue
  • 2XX : 성공
    ex) 200 OK
  • 3XX : 리다이렉트
    ex) 300 Multiple Choices
  • 4XX : 클라이언트 오류
    ex) 400 Bad Request
  • 5XX : 서버 오류
    ex) 500 Internal Server Error


4. request 객체

  • server 객체의 request 이벤트가 발생할 때 이벤트 리스터의 첫 번째 매개변수에 request 객체가 들어간다.
  • request 속성을 사용하면 사용자가 요청한 페이지를 적절하게 제공하는 것은 물론 요청 방식에 따라 페이지를 구분할 수 있다.
[ request 객체의 속성 ]
  • method : 클라이언트의 요청 방식을 나타낸다.
  • url : 클라이언트가 요청한 URL을 나타낸다.
  • headers : 요청 메시지 헤더를 나타낸다.
  • trailers : 요청 메시지 트레일러를 나타낸다.
  • httpVersion : HTTP 프로토콜 버전을 나타낸다.


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

  • 요청 페이지의 URL에 따라 서로 다른 웹 페이지를 제공하는 애플리케이션을 만들어보자.

[ 코드 - index.html 파일 ]

<!DOCTYPE html>

<html>

<head>

    <title>Index</title>

</head>

<body>

    <h1>Hello Node.js _ Index</h1>

    <h2>Author. RintIanTta</h2>

    <hr/>

    <p>Lorem ipsum dolor sit amet</p>

</body>

</html>



[ 코드 - OtherPage.html ]

<!DOCTYPE html>

<html>

<head>

    <title>OtherPage</title>

</head>

<body>

    <h1>Hello Node.js _ OtherPage</h1>

    <h2>Author. RintIanTta</h2>

    <hr/>

    <p>Lorem ipsum dolor sit amet</p>

</body>

</html>


[ 코드 - app.js (페이지 제공) ]

//모듈을 추출한다.

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 == '/') {

        //Index.html 파일을 읽는다.

        fs.readFile('index.html', function (error, data) {

            //응답한다.

            response.writeHead(200, {'Content-Type' : 'text/html'});

            response.end(data);

        })

    } else if (pathname == '/OtherPage') {

        //OtherPage.html 파일을 읽는다.

        fs.readFile('OtherPage.html', function (error, data) {

            //응답한다.

            response.writeHead(200, {'Content-Type' : 'text/html'});

            response.end(data);

        });

    }

}).listen(52273, function() {

    console.log('Server Running at http://127.0.0.1:52273');

});


[ 실행 - http://127.0.0.1:52273 으로 접속했을 때 ]


[ 실행 - http://127.0.0.1:52273/OtherPage 로 접속했을 때 ]

  • URL 에 따른 페이지 구분 하는 것을 확인할 수 있다.

4.2 method 속성을 사용한 페이지 구분
  • GET 요청인지 POST 요청인지에 따른 페이지를 제공하는 것을 하고자 한다.
  • request 객체의 method 속성을 사용하면 요청 방식에 따른 페이지를 쉽게 구분할 수 있다.
[ 코드 - method 속성을 사용한 페이지 구분 ]
//모듈을 추출한다.
var http = require('http');

//모듈을 사용한다.
http.createServer(function (request, response) {
    if (request.method == 'GET') {
        console.log('GET 요청입니다.');
    } else if (request.method == 'POST') {
        console.log('POST 요청입니다.');
    }
}).listen(52273, function() {
    console.log('Server Running at http://127.0.0.1:52273');
});


[ 실행 - method 속성을 사용한 페이지 구분 ]

  • http://127.0.0.1:52273 으로 URL 페이지를 요청하면 GET 방식으로 수행되는 것을 확인할 수 있다.
  • URL을 입력하는 것만으로는 POST 요청을 수행할 수 없다.


4.3 GET 요청 매개변수 추출

[ 코드 - GET 요청 매개변수 추출 ]

//모듈을 추출한다.

var http = require('http');

var url = require('url');


//모듈을 사용한다.

http.createServer(function (request, response) {

    //요청 매개변수를 추출한다.

    var query = url.parse(request.url, true).query;


    //GET 요청 매개변수 출력

    response.writeHead(200, {'Content-Type' : 'text/html'});

    response.end('<h1>' + JSON.stringify(query) + '</h1>');

}).listen(52273, function() {

    console.log('Server Running at http://127.0.0.1:52273');

});

  • url.parse(request.url, true) : true로 입력하면 배열로 파싱한다. 기본값은 false이다.
  • JSON.stringify(query) : 배열을 JSON 문자열로 변환.


[ 실행 - GET 요청 매개변수 추출 ]

  • http://127.0.0.1:52273/?name=rintiantta&region=seoul 로 접속했을 때


4.4 POST 요청 매개변수 추출

  • GET 방식과 달리 POST 방식은 데이터를 더 많이 담을 수 있고 보안 측면에도 좋다.
[ 코드 - HTMLPage.html 파일 ]
<!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>
            <tr>
                <td><label>Data B</label></td>
                <td><input type="text" name="data_b"/></td>
            </tr>
        </table>
        <input type="submit"/>
    </fform>
</body>
</html>
  • POST 매개변수를 입력하는 화면이다.
[ 코드 - request.post.js ]
//모듈을 추출한다.
var http = require('http');
var fs = require('fs');

//모듈을 사용한다.
http.createServer(function (request, response) {
    if (request.method == "GET") {
        //GET 요청
        fs.readFile('HTMLPage.html', function (error, data) {
            response.writeHead(200, {'Content-Type' : 'text/html'});
            response.end(data);
        });
    } else if (request.method == 'POST') {
        //POST 요청
        request.on('data', function (data) {
            response.writeHead(200, {'Content-Type' : 'text/html'});
            response.end('<h1>' + data + '</h1>');
        });
    }
}).listen(52273, function () {
    console.log('Server Running at http://127.0.0.1:52273');
});
  • GET 방식으로 접속할 경우 HTMLPage.html 파일을 제공하고 POST 방식으로 접속할 경우 요청 매개변수를 화면에 출력한다.
[ 실행 - GET 요청 ]

  • GET 방식으로 접속할 경우 HTMLPage.html 파일이 출력된다.
  • Data A와 Data B의 입력 양식에 데이터를 입력하고 [제출] 버튼을 클릭한다.


[ 실행 - POST 요청 ]

  • 앞서 입력했던 데이터가 쿼리 문자열 형태로 출력된다. Query String 모듈을 이용하면 분해하여 원하는 대로 사용할 수 있다.
4.5 쿠키 추출
  • 쿠키는 request 객체의 headers 속성 안 cookie 속성에서 추출할 수 있다.
[ 코드 - 쿠키 생성 및 추출 ]
//모듈을 추출한다.
var http = require('http');

//모듈을 사용한다.
http.createServer(function (request, response) {
    //GET COOKIE
    var cookie = request.headers.cookie;

    //SET COOKIE
    response.writeHead(200, {
        'Content-Type' : 'text/html',
        'Set-Cookie' : ['name = RintIanTta', 'region = seoul']
    });

    //응답한다.
    response.end('<h1>' + JSON.stringify(cookie) + '</h1>');
}).listen(52273, function () {
    console.log('Server Running at http://127.0.0.1:52273');
});

[ 실행 - 처음 접속 ]


[ 실행 - 두 번째 이후 접속 ]

  • 저장된 쿠키가 출력된다.

[ 코드 - 쿠키 분해 ]
//모듈을 추출한다.
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 = RintIanTta', 'region = Seoul']
    });

    //응답한다.
    response.end('<h1>' + JSON.stringify(cookie) + '</h1>');
}).listen(52273, function() {
    console.log('Server Running at http://127.0.0.1:52273');
});
  • 쿠키 값을 split()을 사용하여 ';'로 분해한다.
  • 분해한 값을 다시 '='로 분해한 뒤 key와 value로 구분하여 리턴한다.

[ 실행 -  쿠키 분해 ]

  • 쿠키 값을 key와 value로 분해하여 출력한 화면이다.



'Node.js' 카테고리의 다른 글

Node.js express 모듈  (6) 2015.01.25
Node.js 외부 모듈  (0) 2014.11.12
Node.js 이벤트  (0) 2014.07.06
Node.js 기본 내장 모듈  (2) 2014.06.29
Node.js 전역 객체  (0) 2014.06.25