반응형
05-14 20:55
Today
Total
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
관리 메뉴

개발하는 고라니

[Node.js] Node.js Tutorial (2) 본문

Framework/Node.js

[Node.js] Node.js Tutorial (2)

조용한고라니 2021. 4. 16. 02:59
반응형

Node.js 모듈

모듈은 자바스크립트 라이브러리랑 같다고 여기면 된다.

나의 어플리케이션에 포함시키고 싶은 기능, 함수들을 모아놓은 세트이다.

내장 모듈들

Node는 부가적으로 설치할 필요 없이 사용할 수 있는 내장 모듈 객체를 한 세트 갖고있다. 

 

Node.js Built-in Modules

Node.js Built-in Modules Node.js has a set of built-in modules which you can use without any further installation. Here is a list of the built-in modules of Node.js version 6.10.3: Module Description assertProvides a set of assertion tests bufferTo handle

www.w3schools.com

위의 문서를 보면 수많은 내장 모듈이 있는데 앞으로 몇가지를 천천히 다뤄보도록 하자.

모듈 포함시키기

모듈을 프로그램에서 사용하기 위해서는, 가져오는 작업이 필요한데 Node는 require() 라는 함수를 사용하고 인자로 모듈을 받는다.

const http = require('http');

 


 

Web Server로서의 Node

HTTP 모듈은 서버 포트를 수신하고 클라이언트에게 응답을 반환하는 HTTP Server를 생성할 수 있다.

http의 createServer() 메서드를 사용하면 된다.

const http = require('http');

http.createServer((request, response) => {

	response.write('Hello World');//클라이언트에게 반환할 응답을 작성
    response.end();               //응답의 끝
}).listen(3000);

HTTP Header 추가하기

만약 HTTP Server로부터의 응답이 HTMl로 표현되어야 한다면, 올바른 Content-Type HTTP 헤더를 포함해야만 한다.

const http = require('http');

http.createServer((request, response) => {
    response.writeHead(200, {'Content-Type': 'text/html'});
    response.write('Hello World');
    response.end();
}).listen(3000);

response.writeHead()의 첫 번째 인자로 넣은 200은 OK라는 의미이다. HTTP 통신을 하면 200번대, 400번대, 500번대 숫자를 마주하게 되는데, 200번대는 대개 올바르게 되었다 라고 생각하면 된다.

 

두 번째 인자는 응답헤더를 포함하는 객체를 넣는다.

URL 읽어오기

http.createServer() 메서드의 일부 기능은 request 인자를 갖는다. 클라이언트로부터의 요청을 나타낸다.

 

이 객체는 'url'이라는 속성을 갖는데, 도메인 네임 뒤에 오는 url 부분을 담고있다.

localhost:3000 뒤에 /example이라는 url을 입력했더니 브라우저 화면에 '/example'이라는 url이 등장했다.

QueryString 구분

URL 모듈 같이, 좀더 쉽게 쿼리스트링을 가독성 있게 구분, 분리해주는 내장 모듈이 있다.

const http = require('http');
const url = require('url');

const hostname = 'localhost' //127.0.0.1
const port = 3000;

const server = http.createServer((request, response) => {
    response.statusCode = 200;
    response.setHeader('Content-Type', 'text/plain');
    response.write('Hello World\n');
    
    let qs = url.parse(request.url, true).query; //url.parse()는 URL 객체를 반환하는데, 이때 query속성을 사용하겠다는 것
    let text = qs.x + " " + qs.y + " " + qs.z; //queryString의 x, y, z 파싱해서 사용

    response.write(text);

    response.end();
});

server.listen(port, hostname, () =>{
    console.log(`Server is running at http://${hostname}:${port}`);
});

 

url.parse()는 url String을 받아서 parse하고 URL object로 반환한다.

url.parse( urlString[, parseQueryString[, slashesDenoteHost ]] )

urlString : parse할 Url String

parseQueryString :
> true - 쿼리스트링 모듈의 parse() 메서드에 의해 query 속성이 항상 반환된 객체로 설정된다
> false - 반환된 URL 객체의 query속성이 parse되지 않고, 디코딩되지 않은 문자열로 존재 (default)

slashesDenoteHost : 
> true - '//'의 첫번째를 기준으로 나눠준다. "//foo/bar" => {host: 'foo', pathname: '/bar'}
> false - {pathname: '//foo/bar'}

/example이라는 url 뒤에 x, y, z를 파라미터로 값을 주었고 그것을 파싱해서 브라우저에 출력해보았다. 이처럼 url을 사용하면 간단하게 쿼리스트링과 url을 가져올 수 있다

URL

출처: https://nodejs.org/api/url.html#url_constructing_a_url_from_component_parts_and_getting_the_constructed_string

URL Object의 속성

  • url.auth
  • url.hash
  • url.host
  • url.hostname
  • url.href
  • url.path
  • url.pathname
  • url.port
  • url.protocol
  • url.query
  • url.search
  • url.slashes

# 출처 / Reference

.www.w3schools.com/nodejs/nodejs_http.asp

반응형

'Framework > Node.js' 카테고리의 다른 글

[Node.js] 요청 라우팅 - Router  (0) 2021.04.23
[Node.js] Node.js Tutorial (3) - File System  (0) 2021.04.16
[Node.js] Node.js Tutorial (1)  (0) 2021.04.16
[Node.js] Express Middleware의 Types  (0) 2021.01.08
[Node.js] Middleware 생성  (0) 2021.01.08
Comments