Skip to content
GwiyeomGo Tech Blog
About GwiyeomGo

qs 를 통해 쿼리파람값 받아오자

JAVASCRIPT, 20211 min read

키워드 : querystring,qs,null

문제

데이터를 조회할때 조건 데이터를 querystring 을 통해 서버로 전달합니다. 만약 전달할 객체가 의 속성값이 ""일 경우 ex){status:''} 아래 형태로 서버쪽에 전달되면서 status 가 ''인 경우를 조회했기 때문에 문제가 발생했습니다.

http://localhost:7000/api/admin/donations?page=1&pageSize=10&donationId=&status=

해결방법

npm qs 모듈 사용

모듈qs은 querystring

  • parse하거나
  • stringfy 합니다. stringfy하는 과정에서 null을 skipNull:true 옵션을 사용
const queryString = qs.stringify( location.search,{
arrayFormat:"repeat",
skipNulls:true,
});

(추가 옵션)

  • ignoreQueryPrefix: true :문자열 맨 앞의 ? 생략

  • 라이브러리 사용하지 않고 웹 표준 API인 URLSearchParams 사용해서도 구현 가능

let params = Object.fromEntries(new URLSearchParams(location.search));
  • URL 클래스 ECMAScript 표준의 일부는 아니만 브라우저와 노드에서 잘 동작
let url = new URL("http://test.com");
let params = new URLSearchParams();
params.append("name", "gwiyeom");
url.search = params.toString();
console.log(url.href);
console.log(url.href); // http://test.com/?name=gwiyeom

참고

https://www.daleseo.com/qs-vs-query-string/

© 2024 by GwiyeomGo Tech Blog. All rights reserved.