[ TIL 221202 ] Node.js의 url 모듈 사용하기

ponyo·2022년 12월 2일
0

Node

목록 보기
2/7

url 모듈은 url 정보를 객체로 가져와서 분석(parse)하거나, url 객체를 문자열로 바꿔주는 기능(format, resolve)을 수행

url 모듈 내에서 URL 클래스만 참조하기

const { URL } = require('url');

주소 문자열을 URL 객체로 만들기

const myurl = 'http://www.itpapaer.co.kr:8765/hello/world.html?a=123&b=456#home';
const location = new URL(myurl);
> console.debug(location);

URL {
  href: 'http://www.itpaper.co.kr:8765/hello/world.html?a=123&b=456#home',
  origin: 'http://www.itpaper.co.kr:8765', // 통신 방식 + 사이트 주소 + 포트번호 
  protocol: 'http:', // 통신 방식
  username: '',
  password: '',
  host: 'www.itpaper.co.kr:8765', // 사이트 주소
  hostname: 'www.itpaper.co.kr', // 사이트 주소에서 포트번호를 제외한 값
  port: '8765', // 포트 번호
  pathname: '/hello/world.html', // 사이트 주소에서 변수 영역 제외한 값
  search: '?a=123&b=456', // "?" 를 포함한 변수 영역
  searchParams: URLSearchParams { 'a' => '123', 'b' => '456' }, 
    // search에 저장되어 있는 변수를 key-value의 쌍으로 분리하여 내장하고 잇는 객체
  hash: '#home' // "#"과 함게 표시되는 마지막 값
}

QueryString에서 값을 분리할 때는 URL클래스를 사용하고
JSON에서 QueryString으로 조합할 때는 URLSearchParams를 사용한다.

URLSearchParams

const { URL, URLSearchParams } = require('url');

URL에서 querystring 부분만 추출

const address = 'http://www.itpaper.co.kr:8765/hello/world.html?a=123&b=456';
const { searchParams } = new URL(address);

> console.debug(searchParams);

URLSearchParams { 'a' => '123', 'b' => '456' }

URL에서 추출한 모든 변수는 string타입이다.

> searchParams.get("a"), typeof searchParams.get("a");
123 (string)

> searchParams.get("b"), typeof searchParams.get("b");
456 (string)

객체 타입의 파라미터값을 JSON으로 변환

const params = Object.fromEntries(searchParams);
> console.log(params);

{ a: '123', b: '456' }

JSON 객체를 QueryString 문자열로 변환

URL에 포함될 수 없는 글자는 자동으로 Encoding 처리 함

const obj = { name: 'hello', nick: 'world', 'address': '서울시 서초구' };
const str = new URLSearchParams(obj);

> console.log(str);
URLSearchParams { 'name' => 'hello', 'nick' => 'world', 'address' => '서울시 서초구' }
for (const param of new URLSearchParams(obj)) {
  > console.log(param);
}

[ 'name', 'hello' ]
[ 'nick', 'world' ]
[ 'address', '서울시 서초구' ]
profile
😁

0개의 댓글