기록이 힘이다.

http 모듈 본문

Node.js

http 모듈

dev22 2022. 7. 14. 13:02
728x90

요청과 응답

개념 설명
요청 웹 페이지에 접속하려고 하는 어떤 요청을 말합니다.
응답 요청을 받아 이를 처리하는 작업을 말합니다.
http 모듈 HTTP 웹 서버와 관련된 모든 기능을 담은 모듈입니다.
server 객체 웹 서버를 생성하는 데 꼭 필요한 객체입니다.
response 객체 응답 메시지를 작성할 때 request 이벤트 리스너의 두 번째 매개변수로 전달되는 객체입니다.
request 객체 응답 메시지를 작성할 때 request 이벤트 리스너의 첫 번째 매개변수로 전달되는 객체입니다.

웹 서버가 하는 일은 요청과 응답의 연속이라고 정의할 수 있습니다. 

요청하는 대상을 클라이언트(사용자)라고 부릅니다. 그리고 응답하는 대상을 서버(제공자)라고 부릅니다.

 

1. Server 객체

<포트>

포트는 컴퓨터와 컴퓨터를 연결하는 정보의 출입구 역할을 하는 곳입니다. 일반적으로 웹을 '정보의 바다'라고 표현하는데, 포트는 정보가 정박하고 출발할 수 있는 '항구'입니다. 컴퓨터에는 0번부터 65535번까지 포트가 있습니다.

 

server 객체에서 중요한 것은 메서드보다 이벤트입니다.

더보기

//모듈을 추출합니다.

var http = require('http');

 

//server 객체를 생성합니다.

var server = http.createServer();

 

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

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

    console.log('Request On');

});

 

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

    console.log('Connection On');

});

 

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

    console.log('Close On');

});

 

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

server.listen(52273);

 

2. response 객체

더보기

// 웹 서버를 생성하고 실행합니다.
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');
});

 

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

더보기

// 모듈을 추출합니다.
var fs = require('fs');
var http = require('http');

// 서버를 생성하고 실행합니다.
http.createServer(function (request, response) {
  // HTML 파일을 읽습니다.
  fs.readFile('6-8.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');
});

이미지와 음악 파일 제공

특정 형식 파일을 제공할 때 가장 중요한 것은 응답 헤더의 Content-Type 속성입니다. 

Content-Type 속성은 MiME 형식을 입력  

text/html - HTML 페이지

image/jpeg - 이미지 파일

audio/mp3 - mp3 파일

더보기

// 모듈을 추출합니다.
var fs = require('fs');
var http = require('http');

// 52273번 포트에 서버를 생성하고 실행합니다.
http.createServer(function (request, response) {
  // 이미지 파일을 읽습니다.
  fs.readFile('Chrysanthemum.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');
});

// 52274번 포트에 서버를 생성하고 실행합니다.
http.createServer(function (request, response) {

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

 

 

 

쿠키 생성

쿠키는 키와 값이 들어 있는 작은 데이터 조각으로 이름, 값, 파기 날짜와 경로 정보가 있습니다. 쿠키는 서버와 클라이언트에서 모두 저장하고 사용할 수 있으며, 일정 기간 동안 데이터를 저장할 수 있으므로 로그인 상태를 일정 시간 동안 유지해야 하는 페이스북과 같은 웹 사이트에 사용합니다.

response 객체를 사용하면 클라이언트에 쿠키를 할당할 수 있습니다. 이때는 응답 헤더의 Set-Cookie 속성을 사용합니다. Set-Cookie 속성에는 다음과 같은 문자열 형태로 이루어진 쿠키의 배열을 넣습니다.

더보기

Name = Value; Expires = 날짜; Domain = 도메인; Path = 경로; Secure

 

 

 

 

// 모듈을 추출합니다.
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(52273, function () {
  console.log('Server Running at http://127.0.0.1:52273');
});

 

페이지 강제 이동

더보기

// 모듈을 추출합니다.
var http = require('http');

// 웹 서버를 생성 및 실행합니다.
http.createServer(function (request, response) {
  response.writeHead(302, { 'Location': 'http://www.hanbit.co.kr' });
  response.end();
}).listen(52273, function () {
  console.log('Server Running at http://127.0.0.1:52273');
});

3. request 객체

속성 이름 설명
method 클라이언트의 요청 방식을 나타냅니다.
url  클라이언트가 요청한 URL을 나타냅니다.
headers 요청 페이지 헤더를 나타냅니다.
trailers  요청 메시지 트레일러를 나타냅니다.
httpVersion HTTP 프로토콜 버전을 나타냅니다.

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

더보기
// 모듈을 추출합니다.
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('6-17.html', function (error, data) {
            // 응답합니다.
            response.writeHead(200, { 'Content-Type': 'text/html' });
            response.end(data);
        });
    } else if (pathname == '/OtherPage') {
        // OtherPage.html 파일을 읽습니다.
        fs.readFile('6-18.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');
});

Node.js는 기본적으로 페이지를 요청할 때 대소문자를 구분합니다. 

 

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

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');
});

POST  요청 매개변수 추출

GET 방식과 달리 데이터를 더 많이 담을 수 있고 보안 측면에서도 좋습니다. GET 방식은 요청하면서 매개변수 형식으로 노출되어 데이터를 전달하지만 POST 방식은 요청한 후 데이터를 별도로 전달하기 때문입니다.

더보기
// 모듈을 추출합니다.
var http = require('http');
var fs = require('fs');

// 모듈을 사용합니다.
http.createServer(function (request, response) {
    if (request.method == 'GET') {
        // GET 요청
        fs.readFile('6-25.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');
});

쿠키 추출

더보기
// 모듈을 추출합니다.
var http = require('http');

// 모듈을 사용합니다.
http.createServer(function (request, response) {
    // 쿠키가 있는지 확인
    if (request.headers.cookie) {
        // 쿠키를 추출하고 분해합니다.
        var cookie = request.headers.cookie.split(';').map(function (element) {
            var element = element.split('=');
            return {
                key: element[0],
                value: element[1]
            };
        });

        // 응답합니다.
        response.end('<h1>' + JSON.stringify(cookie) + '</h1>');
    } else {
        // 쿠키를 생성합니다.
        response.writeHead(200, {
            'Content-Type': 'text/html',
            'Set-Cookie': ['name = RintIanTta', 'region = Seoul']
        });

        // 응답합니다.
        response.end('<h1>쿠키를 생성했습니다</h1>');
    }
}).listen(52273, function () {
    console.log('Server Running at http://127.0.0.1:52273');
});

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

이벤트  (0) 2022.07.07
Node.js 기본  (0) 2022.06.29
Node.js  (0) 2022.06.29