ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [생활코딩] Node.js 강의 4일차
    Node.js 2021. 6. 21. 13:01

    App - Not found 오류 구현 ,홈페이지 구현

    1. 강의 내용
      강의 목표는 다음과 같다.
      1. 사용자가 query string 없는 home으로 들어오게 되면 wlelcome page 출력
      2. 사용자가 목록을 클릭해서 query string 있는 (id값이 있는 ) 주소로 접속하면 id값에 해당되는 파일을 data  directory에서 찾아서 웹페이지를 생성 
      3.  외의 주소로 돌아왔을때 파일을 찾을  없다라는 오류 메시지를 사용자에게 전송 
      1) 위의 기능을 만들기 위해서 우선 사용자가 root로 접근했는지 안했는지 알아내야한다.  url 이 가지고 있는 정보를 통해 pathname과 path를 알 수 있다. 
      //url이 가지고 있는 정보 출력 
      console.log(url.parse(_url,true)); 
      /* 
      Url { 
      	protocol: null, slashes: null, auth: null, host: null, port: null,
      	hostname: null, hash: null, search: '?id=HTML', query: { id: 'HTML' },
          pathname: '/', path: '/?id=HTML', href: '/?id=HTML' 
           } 
      */​

      2) pathname 이 root ('/') 와 같으면 1,2번 기능을 같지 않다면 오류메시지를 전송한다.
      같을 때 response.writeHead(200); 그렇지 않은 경우 response.writeHead(404);  로 명확하게 헤더를 작성해준다. 
      (명시적인 헤더 데이터 전송에 관한 설명 : https://nodejs.org/ko/docs/guides/anatomy-of-an-http-transaction/)

      Http 상태코드 (https://developer.mozilla.org/ko/docs/Web/HTTP/Status)
      200 : 요청이 성공적 
      400 : Bad Request . 잘못된 문법으로 서버가 요청을 이해할 수 없음
      404 : Not Found . 요청받은 리소스를 찾을 수 없음

      3) home과 목록의 페이지들을 pathname 하나만으로 구분할 수 없기에 query 데이터를 이용해 queryString의 id가 undefined면 웰컴 페이지를 출력하고 아니라면 각각의 query에 맞는 페이지를 출력하도록 한다. 
          if(pathname ==='/'){
            if(queryData.id === undefined){
            	... //웰컴페이지
              } else{
              ... // 각 queryString에 맞는 페이지 
              }
           } else{...}
             

                                                
    2. 강의 코드
      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;
          var pathname = url.parse(_url,true).pathname;
          
          //console.log(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>
                  <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>${description}</p>
                </body>
                </html>
              `;
              response.writeHead(200);
              response.end(template);
              });
            }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>
                  <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>${description}</p>
                </body>
                </html>
              `;
              response.writeHead(200);
              response.end(template);
              });
            }
          } else {
              response.writeHead(404);
              response.end('Not found');
          }
      });
      app.listen(3000);​
     

    HTTP 상태 코드 - HTTP | MDN

    HTTP 응답 상태 코드는 특정 HTTP 요청이 성공적으로 완료되었는지 알려줍니다. 응답은 5개의 그룹으로 나누어집니다: 정보를 제공하는 응답, 성공적인 응답, 리다이렉트, 클라이언트 에러, 그리고

    developer.mozilla.org

     


    Node.js - 파일 목록 알아내기 & App - 글 목록 출력하기  

    1. 강의 내용
      강의 목표는 다음과 같다.
      1. 글목록의 데이터를 추가하면 코드를 수정하지 않고 nodejs가  반영할 수 있게 하기
      2. 리스트 추가, 수정, 작동 자동화
      1) 글 목록의 데이터 폴더에 어떤 파일들이 있는지 node.js가 읽을 수 있게 한다.
      //fs.readdir을 이용하자
      
      var testFolder = './data';
      var fs = require('fs');
       
      fs.readdir(testFolder, function(error, filelist){
        console.log(filelist);
      })​
       
      아래와 같은 결과가 출력된다.
      readdir.js 결과

      2) 반복문으로 폴더안의 파일이 있는 만큼 리스트를 만들 수 있도록 한다.
      fs.readdir('./data',function(error,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>`;​
      })
      
      
       data 폴더에 Nodejs파일을 추가하면 리스트에 nodejs파일 추가 코드를 쓰지 않아도 아래와 같이 페이지에 반영된다.
      list 자동화 수정 결과
    2. 강의 코드
      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;
          var pathname = url.parse(_url,true).pathname;
      
          if(pathname ==='/'){
            if(queryData.id === undefined){
      
              fs.readdir('./data',function(error,filelist){
                var title = 'Welcome';
                var description  = 'Hello Node.js'
                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>`;
                var template = ` 
                  <!doctype html>
                  <html>
                  <head>
                    <title>WEB1 - ${title}</title>
                    <meta charset="utf-8">
                  </head>
                  <body>
                    <h1><a href="/">WEB</a></h1>
                      ${list}
                    <h2>${title}</h2>
                    <p>${description}</p>
                  </body>
                  </html>
                `;
                response.writeHead(200);
                response.end(template);
             
            })
      
            }else{
              fs.readdir('./data',function(error,filelist){
                var title = 'Welcome';
                var description  = 'Hello Node.js'
                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>`;
                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>
                    ${list}
                    <h2>${title}</h2>
                    <p>${description}</p>
                  </body>
                  </html>
                `;
                response.writeHead(200);
                response.end(template);
                });
              });
            }
          } else {
              response.writeHead(404);
              response.end('Not found');
          }
      
       
      });
      app.listen(3000);​

    App - 함수를 이용해서 정리 정돈하기

    1. 강의 내용
      강의 목표 : 함수 이용해 코드 중복 제거 
      1) templateHTML
      인자 title, list, body. <h2>${title}</h2>${description}은 앞으로 내용이 바뀔 수도 있기에 ${body}로 처리해줌. 
      2) templateList 
      filelist가 있어야 반복문이 작동할 수 있기 때문에 인자로 filelist를 취해줌.
    2. 강의 코드 
      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;
          var pathname = url.parse(_url,true).pathname;
      
          if(pathname ==='/'){
            if(queryData.id === undefined){
              fs.readdir('./data',function(error,filelist){
                var title = 'Welcome';
                var description  = 'Hello Node.js'
                var list = templateList(filelist);
                var template = templateHTML(title,list,`<h2>${title}</h2>${description}`);
                response.writeHead(200);
                response.end(template);
              })
            }else{
              fs.readdir('./data',function(error,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>${description}`);
                  response.writeHead(200);
                  response.end(template);
                });
              });
            }
          } else {
              response.writeHead(404);
              response.end('Not found');
            }
      });
      app.listen(3000);​
Designed by Tistory.