[App] 동적인 웹페이지 만들기

mingguriguri·2022년 5월 17일
0

Node.js

목록 보기
8/21

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

  • 지난시간 : QueryString을 추출하는 과정 배움
    (QueryString은 id값 부분임!)

  • 이번 시간 : 우리가 직접 치지 않아도 클릭할 시, 동적으로 변할 수 있게 코드를 수정할 예정

1. template literary 변수 생성
-> 백틱(``) 잊지 말기
-> 1.html의 내용 복사해서 가져오기
-> 가져오고 싶은 데이터는 ${ } 을 이용

2. 웹페이지의 주소를 동적으로 수정 (우리가 직접 칠 때마다 바뀌는 게 아니라, 클릭 시 자동으로 변경)
-> 우리가 가져온 주소, 즉 querystring을 이용!
-> 가져올 땐 더 깔끔하기 위해 qureyData.id를 저장하는 title변수 생성

3. 홈의 주소 url을 /으로 변경
/로 변경하면, if문으로 가게 됨. 그때 title의 값을 'Welcome!'으로 수정

4. <ol><ul> 로 변경!
-> 웹페이지가 무수해도 상관없이 동적으로 ${title} 변화 가능


완성 코드

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 = new URL('http://localhost:3000' + _url).searchParams;
  var title = queryData.id;
  console.log(queryData.get('id'));
  if(_url == '/'){
    //홈으로 갔을 때 이 부분을 실행!
    title = 'Welcome!';
    }
    if(_url == '/favicon.ico'){
      response.writeHead(404);
      response.end();
      return;
    }
    response.writeHead(200);
//console.log(__dirname + url);
    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>

    `;
    response.end(template);

});
app.listen(3000);

결과

⭐주소창을 유의하여 봐주세요!

WEB

HTML

CSS

JavaScript


느낀 점

  • 아직 잘 감은 안 오지만, 지난 시간의 QueryString을 이용하는 것을 보니까 조금은 연결되는 느낌이 듬
  • 개념을 차곡차곡 쌓는 과정이라는 생각이 듬
profile
To be "irreplaceable"

0개의 댓글