url 모듈
은 url 정보를 객체로 가져와서 분석(parse)하거나, url 객체를 문자열로 바꿔주는 기능(format, resolve)을 수행
const { URL } = require('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
를 사용한다.
const { URL, URLSearchParams } = require('url');
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' }
> searchParams.get("a"), typeof searchParams.get("a");
123 (string)
> searchParams.get("b"), typeof searchParams.get("b");
456 (string)
const params = Object.fromEntries(searchParams);
> console.log(params);
{ a: '123', b: '456' }
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', '서울시 서초구' ]