Notice
Recent Posts
Recent Comments
Link
«   2024/03   »
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
Archives
Today
Total
관리 메뉴

차근차근

[Node.js] 동적 웹페이지 만들기 본문

대학교/BE

[Node.js] 동적 웹페이지 만들기

SWKo 2020. 2. 14. 19:57

0. URL

  • http://opentutorials.org:3000/main?id=HTML&page=12 
  • http -> protocol
  • opentutorials.org -> host(domain)(인터넷에 접속되어 있는 각각의 컴퓨터를 host라고 한다.)
  • 3000 -> port(한 대의 컴퓨터에 여러 대의 서버가 있을 수 있다. 그러면 클라이언트가 접속했을 때 어떤 서버와 연결할지 애매하다. 그래서 port를 설정해준다.
  • main -> path
  • id=HTML&page=12 -> query string(웹서버에 데이터를 전달할 수 있다. 시작은 ?로 함. 값과 값은 &로 구분한다.

1. 동적인 웹페이지 만들기

  • http://localhost/?id=HTML 에서 id=HTML을 query string이라고 한다. 
  • query string 에 따라 다른 웹페이지를 보여주는 것을 해보겠다.
  • 본문은 그대로 있고 제목은 바뀌는 코드
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
var http = require('http');
var fs = require('fs');
var url = require('url');
 
var app = http.createServer(function(request,response){
    var _url = request.url;
    var title = queryData.id;
    if(_url == '/'){
      title = 'Welcome';
    }
    if(_url == '/favicon.ico'){
      return response.writeHead(404);
    }
    response.writeHead(200);
    var template = `
    <!doctype html>
    <html>
    <head>
      <title>WEB1 - ${title}</title>
      <meta charset="utf-8">
    </head>
    <body>
      <h1><a href="/">WEB</a></h1>
      <ol>
        <li><a href="/?id=HTML">HTML</a></li>
        <li><a href="/?id=CSS">CSS</a></li>
        <li><a href="/?id=JavaScript">JavaScript</a></li>
      </ol>
      <h2>${title}</h2>
      <p><a href="https://www.w3.org/TR/html5/" target="_blank" title="html5 speicification">Hypertext Markup Language (HTML)</a> is the standard markup language for <strong>creating <u>web</u> pages</strong> and web applications.Web browsers receive HTML documents from a web server or from local storage and render them into multimedia web pages. HTML describes the structure of a web page semantically and originally included cues for the appearance of the document.
      <img src="coding.jpg" width="100%">
      </p><p style="margin-top:45px;">HTML elements are the building blocks of HTML pages. With HTML constructs, images and other objects, such as interactive forms, may be embedded into the rendered page. It provides a means to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists, links, quotes and other items. HTML elements are delineated by tags, written using angle brackets.
      </p>
    </body>
    </html>
    
   `;
 
});
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

2. Node.js의 파일 읽기 기능

  • CRUD(Create, Read, Update, Delete)

 

3. 파일을 이용해 본문 구현

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
var http = require('http');
var fs = require('fs');
var url = require('url');
 
var app = http.createServer(function(request,response){
    var _url = request.url;
    var queryData = url.parse(_url, true).query;//query string 추출
    var pathname = url.parse(_url, true).pathname;
    var title = queryData.id;
    
    if(pathname === '/'){
      fs.readFile(`data/${queryData.id}`, 'utf8'function(err, description){
        var template = `
      <!doctype html>
      <html>
      <head>
        <title>WEB1 - ${title}</title>
        <meta charset="utf-8">
      </head>
      <body>
        <h1><a href="/">WEB</a></h1>
        <ul>
          <li><a href="/?id=HTML">HTML</a></li>
          <li><a href="/?id=CSS">CSS</a></li>
          <li><a href="/?id=JavaScript">JavaScript</a></li>
        </ul>
        <h2>${title}</h2>
        <p>${description}</p>
      </body>
      </html>
      `;
      response.writeHead(200);
      response.end(template);//우리가 만든파일을 읽어서 그 값을 가져와서 response.end를 통해서 작동시킨다.
      });
    }else{
      response.writeHead(404);
      response.end('Not Found');
    }
 
});
 
 
  • url의 구성을 보기 위해 console.log(url.parse(_url, true)); 를 실행해보면 다음과 같은 결과가 나온다.

  • 웹서버는 브라우저에게 특정한 숫자를 돌려준다.
  • response.writeHead(200) 과 같이 사용한다.

4. 홈페이지 구현

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
var http = require('http');
var fs = require('fs');
var url = require('url');
 
var app = http.createServer(function(request,response){
    var _url = request.url;
    var queryData = url.parse(_url, true).query;//query string 추출
    var pathname = url.parse(_url, true).pathname;
        
    if(pathname === '/'){
      if(queryData.id === undefined){
        fs.readFile(`data/${queryData.id}`, 'utf8'function(err, description){
          var title = 'Welcome';
          var description = 'Hello, Node.js';
          var template = `
        <!doctype html>
        <html>
        <head>
          <title>WEB1 - ${title}</title>
          <meta charset="utf-8">
        </head>
        <body>
          <h1><a href="/">WEB</a></h1>
          <ul>
            <li><a href="/?id=HTML">HTML</a></li>
            <li><a href="/?id=CSS">CSS</a></li>
            <li><a href="/?id=JavaScript">JavaScript</a></li>
          </ul>
          <h2>${title}</h2>
          <p>${description}</p>
        </body>
        </html>
        `;
        response.writeHead(200);
        response.end(template);//우리가 만든파일을 읽어서 그 값을 가져와서 response.end를 통해서 작동시킨다.
        });
      }else{
        fs.readFile(`data/${queryData.id}`, 'utf8'function(err, description){
          var title = queryData.id;
          var template = `
        <!doctype html>
        <html>
        <head>
          <title>WEB1 - ${title}</title>
          <meta charset="utf-8">
        </head>
        <body>
          <h1><a href="/">WEB</a></h1>
          <ul>
            <li><a href="/?id=HTML">HTML</a></li>
            <li><a href="/?id=CSS">CSS</a></li>
            <li><a href="/?id=JavaScript">JavaScript</a></li>
          </ul>
          <h2>${title}</h2>
          <p>${description}</p>
        </body>
        </html>
        `;
        response.writeHead(200);
        response.end(template);//우리가 만든파일을 읽어서 그 값을 가져와서 response.end를 통해서 작동시킨다.
        });
      }
    }else{
      response.writeHead(404);
      response.end('Not Found');
    }
 
});
 
 
  • node [해당파일] 명령어를 실행시켜보면 pathname과 query string에 따라 다르게 나오는 홈페이지를 볼 수 있다.

5. Node.js 에서 파일목록 알아내기


6. 함수를 적용시킨 코드

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
var http = require('http');
var fs = require('fs');
var url = require('url');
 
function templateHTML(title, list, body){
            return `
            <!doctype html>
            <html>
            <head>
            <title>WEB1 - ${title}</title>
            <meta charset="utf-8">
            </head>
            <body>
            <h1><a href="/">WEB</a></h1>
            ${list}
            ${body}
            </body>
            </html>
            `
}
 
function templateList(filelist){
    var list = '<ul>';
    
    var i = 0;
    while(i < filelist.length){
        list = list + `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`;
        i = i + 1;
    }
 
    list = list+'</ul>';
    return list;
}
 
var app = http.createServer(function(request,response){
    var _url = request.url;
    var queryData = url.parse(_url, true).query;//query string 추출
    var pathname = url.parse(_url, true).pathname;
        
    if(pathname === '/'){
      if(queryData.id === undefined){
 
        fs.readdir('./data'function(err, filelist){
            var title = 'Welcome';
            var description = 'Hello, Node.js';
            
            var list = templateList(filelist);
 
            var template = templateHTML(title, list, `<h2>${title}</h2><p>${description}</p>`);
          response.writeHead(200);
          response.end(template);//우리가 만든파일을 읽어서 그 값을 가져와서 response.end를 통해서 작동시킨다.
        });
 
      }else{
        fs.readdir('./data'function(err, filelist){
            fs.readFile(`data/${queryData.id}`, 'utf8'function(err, description){
            var title = queryData.id;
            var list = templateList(filelist);
            var template = templateHTML(title, list, `<h2>${title}</h2><p>${description}</p>`);
            response.writeHead(200);
            response.end(template);//우리가 만든파일을 읽어서 그 값을 가져와서 response.end를 통해서 작동시킨다.
            });
        });
      }
    }else{
      response.writeHead(404);
      response.end('Not Found');
    }
 
});
 

'대학교 > BE' 카테고리의 다른 글

[Node.js] Object & Module  (0) 2020.02.18
[Node.js] CRUD  (0) 2020.02.15
[Node.js] 간단한 웹 서버 만들기  (0) 2020.02.14
[Node.js] 노드의 기본 기능  (0) 2020.02.12
[Node.js] 노드 & 자바스크립트  (0) 2020.02.12
Comments