N
7. Node.js URL 본문
생활코딩 강의를 바탕으로 쓴 글입니다 :)
동적인 웹 페이지 만들기
지난번 만들었던 웹 페이지에서 WEB, HTML, CSS, JavaScript를 클릭 했을 때 동적으로 변하는 웹 페이지를 만들어 보도록 하겠습니다.
간단한 설명을 위해 html.html 파일에서 모든 코드를 복사하겠습니다.
그 후 main.js에 template라는 변수로 저장하도록 하겠습니다.
const http = require("http");
const fs = require("fs");
const url = require("url");
const app = http.createServer((req, res) => {
var _url = req.url;
var queryData = url.parse(_url, true).query;
var title = queryData.id;
console.log(queryData.id);
if (_url == "/") {
title = "Welcome";
}
if (_url == "/favicon.ico") {
return res.writeHead(404);
}
res.writeHead(200);
var template = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WEB1 - ${title}</title>
</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 specification"
>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="./html.jpg" width="100%" alt="img" />
</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>
`;
res.end(template);
});
app.listen(3000);
몇 가지 추가된 부분이 있습니다.
queryData가 추가된 것을 확인할 수 있습니다.
가끔 인터넷을 하다가 브러우저 주소창을 보면
이렇게 뒷 부분에 ?가 있는 부분을 확인할 수 있습니다.
이는 쿼리문으로 무엇인가 검색할 때 주로 확인할 수 있습니다.
사용자가 원하는 데이터를 검색할 때 그에 맞는 결과를 보여줌으로써 웹 페이지를 이동하는 것입니다.
위 코드로 수정한 후 주소를 입력해보겠습니다.
localhost:3000/?id=HTML
을 입력한 후 브라우저를 확인하면 아래와 같은 결과를 얻게 됩니다.
즉 /?id=~ 이 부분이 쿼리가 되고, 입력된 쿼리문에 따라 결과를 다르게 보여주는 것이 동적인 웹페이지라고 할 수 있겠습니다.
쿼리문을
/?id=CSS
/?id=JavaScript
로 입력하면 제목 부분이 바뀌는 것을 확인할 수 있습니다.
하지만 내용은 바뀌지 않습니다.
왜냐하면 제목 부분만 바뀌게 했을 뿐 본문의 내용은 클릭하거나 쿼리문을 변경해도 template 변수 안에 있는 내용을 바뀌지 않게 했기 때문입니다.
다음에는 지금까지 만들었던 html.html, css.html, js.html 파일을 읽어 제목과 본문을 동적으로 변하게 하도록 해보겠습니다.
'Node.js' 카테고리의 다른 글
8. Node.js 파일을 읽어 본문 내용 바꾸기 (0) | 2021.02.02 |
---|---|
6. Node.js (9) | 2021.01.20 |
5. bitnami를 이용한 웹 서버 운영 (0) | 2021.01.15 |
4. HTML 웹 페이지 이동 (0) | 2021.01.08 |
3. HTML Tag(table, a, img, iframe) (0) | 2021.01.08 |