본문 바로가기
프로그래밍 개발/NodeJs

Node.js - URL와 query string

by Jinseok Kim 2020. 12. 5.
반응형

 

 

 

URL

 

 

 

 

  • 위의 설명은 URL의 기본 구조이다. 여기서 중요한 것은 query string이다.
  • 쿼리 스트링에 따라서 데이터를 출력하고 또 그 데이터들을 바꿀수 있다는 사실을 알아야 한다.

 

 

 

 

 

 

 

 query string의 성질 알아보기 예제 실험

 

var http = require('http');
var fs = require('fs');
var url = require('url');
 
var app = http.createServer(function(request,response){
    var _url = request.url;
    // 쿼리 데이터를 추출하게끔 3행에서 url이라는 모듈을 사용한다고 변수를 선언해주고 
    //8,9행의 코드를 추가시켰다.
    var queryData = url.parse(_url, true).query;
    console.log(queryData.id);
    if(_url == '/'){
      _url = '/index.html';
    }
    if(_url == '/favicon.ico'){
      return response.writeHead(404);
    }
    response.writeHead(200);
    response.end(queryData.id);
 
});
app.listen(3000);

위의 코드는 웹의 자바스크립트 코드이다. 이 코드에서 특별히 쿼리 스트링에 대하여 알아보기 위하여 쿼리 데이터의 값을 추출하는 코드를 추가시켰다.

 

 

 

 

 

 

 

 

 

위의 자바스크립트 데이터 값을 가지고 있는 웹의 쿼리 데이터에 jinseok으로 적어주자 명령 프롬프트에 쿼리 데이터가 jinseok으로 추출된 것을 확인 할 수있다.

 

 

 

 

 

 

 

 

 

 

동적인 웹 페이지

 

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;
    
    //추출한 쿼리 데이터를 변수 title로 지정해줌. 그리고 template의 변수로 지정한
    // html 파일 코드의 <title>값</title>의 값으로 ${title}을 지정해준다.
    var title = queryData.id;
    
    //if문 조건으로 /을 변수로 지정된 _url이 실행되면 title 값이 Hi jin seok!으로 바꾸게 함
    if(_url == '/'){
      title = 'Hi jin seok!';
    }
    if(_url == '/favicon.ico'){
      return response.writeHead(404);
    }
    response.writeHead(200);
    // template 이라는 변수로 html1의 html 파일 코드 전체를 지정함. 
    var template = `
    <!doctype html>
    <html>
    <head>
      <title>WEB1 - ${title}</title>
      <meta charset="utf-8">
    </head>
    <body>
      <h1><a href="/">WEB</a></h1>
      <ul>
      <!--아래 해당 링크를 클릭하면 <title>값</title>의 값이 설정한 쿼리 데이터로 변환되도록 설정함.-->
        <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>
    `;
    
    //template 변수 호출
    response.end(template);
 
});
app.listen(3000);

코드를 모두 작성했으면 노드를 이용하여 명령을 코드 실행 입력해주어야 한다.

 

 

 

  • 쿼리 데이터를 추출한 변수 title를 이용하여 쿼리 데이터 값을 jinseok으로 했더니 <title></title>이 jinseok으로 바뀐 것을 확인 할 수있다. 왜냐하면 쿼리 데이터 추출한 변수를  <title></title> 요소 값으로 지정해주었기 때문이다.
  • 또 WEB 링크를 클릭하면 쿼리 데이터를 추출한 변수 title의 값을 'Hi jinseok!' 문자로 변환되도록 하여 쿼리 데이터 추출한 변수를  <title></title> 요소 값으로 지정하였기에  <title></title>이  'Hi jinseok!'의 문자로 변환되었다.

 

 

 

 

 

 

반응형

'프로그래밍 개발 > NodeJs' 카테고리의 다른 글

Node.js - 홈페이지 구현  (0) 2020.12.05
Node.js - 콘솔에서의 입력값  (0) 2020.12.05
Node.js - 파일 읽기  (0) 2020.12.05
Node.js - javascript 기본 언어 실행  (0) 2020.12.05
Node.js 실행 방법  (0) 2020.12.05

댓글