세리프 따라잡기

nodejs에서 template literals과 URL에 대해 본문

Node.js

nodejs에서 template literals과 URL에 대해

맑은 고딕 2020. 12. 31. 21:41

 

1. template literals(`)에 대해

var name = 'gothic';
var letter = 'To. '+name+'.\n\ndkanrjsk gothic rmsid '+name+' cuqhqslek. '+name; //줄바꿈이 필요할 때는 \n 을 써주면 된다.

// 리터럴(literal)은 정보를 표현하는 방법, 기호이다.

var letter = `To. ${name}.

dkanrjsk ${1+1} gothic rmsid ${name} cuqhqslek. ${name}`; // `(template literals)를 사용하면 줄바꿈(\n)을 안 사용해도 되고, 변수를 사용할 때도 ${변수 이름}을 사용하여 더 간편하게 할 수 있다. 뿐 아니라 ${}안에 넣으면 변수로 치환이 된다. [ex. 결과값에 2 표시]

console.log(letter);

 

 

2. URL에 대해

아래는 샘플 URL

http://malgun-gothic.tistory.com/main?id=HTML&page=991617

 

http(hypertext transfer protocol): 웹 브라우저와 웹 서버가 서로 데이터를 주고 받기 위해서 만든 통신 규칙. 만약 ftp를 사용한다면 ftp로 표기된다.
host(domain): 인터넷에 접속되어 있는 각각의 컴퓨터를 호스트라 하고, '.com'은 특정한 인터넷에 연결되어 있는 주소를 가리킨다.
port: 웹서버의 기본 포트값이 '80'이다. 따라서 malgun-gothic.tistory.com:80/main?id=HTML&page=991617 이렇게 주소를 쳐도 http를 이용해 웹서버에 접속한다는 뜻이 된다.
path: 컴퓨터 안에 있는 어떤 디렉토리의 어떤 파일인지를 가리킨다.
query string: 지금 배울 주인공. 이 값을 변경하면 웹 서버에게 데이터를 전달할 수 있다. 쿼리 스트링의 시작은 '?'이다. 값과 값은 &로 쓰고, 값의 이름과 값은 =로 구분한다.

 

3. URL을 통해 입력값 사용하기

  • 변수값 출력(?)
var http = require('http');
var fs = require('fs');

var app = http.createServer(function (request, response) {
    var _url = request.url;
    console.log(_url); // 주소를 http://localhost:3000/?id=HTML 이라고 하고 로딩하면, 결과값은 에러이나, 이 URL의 변수값인 데이터(/?id=HTML)가 윗줄에 표시된다. 만약 CSS라고 친다면 (/?id=CSS) 라고 표기됨.
    if (_url == '/') {
        _url = '/index.html';
    }
    if (_url == '/favicon.ico') {
        response.writeHead(404);
        response.end();
        return;
    }
    response.writeHead(200);
    response.end(fs.readFileSync(__dirname+_url)); // 사용자가 접속한 url에 따라서 이 안에 있는 파일들을 읽어주는 코드이다.

});
app.listen(3000);
  • 출력2
var http = require('http');
var fs = require('fs');
var url = require('url'); // require는 http, fs, url(이를 모듈(nodejs가 갖고 있는 수많은 기능들을 비슷한 요건끼리 그룹핑 한 것)이라 한다)을 요구한다. 여기서의 뜻은 url이라는 노드를 url이라는 변수를 통해 사용할 거라는 거를 뜻함.

var app = http.createServer(function (request, response) {
    var _url = request.url; //_(언더바)를 붙인 이유는 앞의 모듈 URL과 겹치지 않게 하기 위해.
    var querydata = url.parse(_url, true).query;
    console.log(querydata.id); //(querydata); 까지만 쓴다면 결과값은 { id: 'HTML' }이 나온다. 이는 쿼리데이터라는 변수 안에 담긴 것이 객체기 때문이다. (querydata.id); 라고 쓴다면 값은 HTML 라고 출력된다.
    if (_url == '/') {
        _url = '/index.html';
    }
    if (_url == '/favicon.ico') {
        response.writeHead(404);
        response.end();
        return;
    }
    response.writeHead(200);
    response.end(querydata.id); // 출력값에 HTML이라고만 찍히고, 동시에 브라우저 상에도 HTML 라고 찍힌다.

});
app.listen(3000);

+)위 코드 8번째 칸의 출력 [object: null prototype]에 대해

stackoverflow.com/questions/56298481/how-to-fix-object-null-prototype-title-product

 

how to fix [Object: null prototype] { title: 'product' }

I've started learning node.js with express framework , when I post a form like this : router.get('/add-product',(req,res,next)=>{ res.send('

<...

 

stackoverflow.com

= 제대로 이해한 것이 맞다면, 결론적으로 결과값에 [object: null prototype] { id = HTML } 이라고 뜨는 것은 특별히 고칠 필요는 없는 부분인 것 같다. 만약 이게 거슬린다면 아래와 같이 코드를 쓰면 된다. [ 문법: JSON.stringify() ]

console.log(JSON.stringify(querydata));

4. 쿼리 스트링에 따라서 완성된 웹페이지를 표현해보기 [동적 웹페이지]

  • 타이틀 동적 변경하기
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;
    console.log(querydata.id);
    if (_url == '/') {
        _url = '/index.html';
    }
    if (_url == '/favicon.ico') {
        response.writeHead(404);
        response.end();
        return;
    }
    response.writeHead(200);
    var template = `
    <!doctype html>
<html>
<head>
  <title>WEB1 - ${querydata.id}</title>
  <meta charset="utf-8">
</head>
<body>
  <h1><a href="index.html">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>${querydata.id}</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>
    `; //template litarals 사용. 안의 내용은 본인 1.html 파일을 카피한 것. title 부분과 h2 부분을 동적으로 변경되게끔 ${querydata.id}를 사용한다. + li 부분의 주소를 "/?id=ㅁㅁ"라고 변경하면 클릭과 동시에 동적으로 제목과 타이틀이 변경되는 것을 볼 수 있다.
    response.end(template); //안의 h2 부분과 title 부분이 쿼리 데이터 id 부분에 입력한 것과 동일하게 변경되는 것을 볼 수 있다. (ex. asd라 입력하면 asd라고 출력되며 동시에 브라우저 상에도 바뀌는 것을 볼 수 있음)

});
app.listen(3000);
  • 위 코드를 더 깔끔하고 동적이게 바꾸기
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 title = querydata.id; // title이란 변수를 지정함으로써 밑의 ${querydata.id} 부분을 좀 더 깔끔한 코드로 변경.
    if (_url == '/') { // 조건문. 만약 _url이 /라면 title을 welcome 으로 표시하라. → 이 부분은 밑 template 부분 h1의 "/" 를 뜻함.
        title = 'Welcome';
    }
    if (_url == '/favicon.ico') {
        response.writeHead(404);
        response.end();
        return;
    }
    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>
  <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><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>
    `; // 순서 있는 리스트(ol)를 없는 리스트로 바꾸라고 지시를 내렸을 때 <ol> 부분을 <ul> 라고만 바꾸면 다 바꿀 수 있다는 것!! 효율성이 최고다.
    response.end(template);

});
app.listen(3000);
Comments