서버 GET 요청의 Query로 배열값을 받아야할 때, 프론트에서는 어떻게 전달하면 될까?
BACKEND
TYPESCRIPT
서버 GET Query로 배열값을 받아야할 때,프론트에서는 어떻게 전달하면 될까요?
https://api.test.com?tech=nest.js&tech=next.js&tech=react
서버에서는 QueryString값으로 받아야할 값(tech)이 다음과 같이 지정되어있다고 해봅시다.
import { ApiPropertyOptional } from "@nestjs/swagger";
import { Transform } from "class-transformer";
import {
IsArray,
IsEnum,
IsOptional,
IsString,
} from "class-validator";
export class GetConceptListRequestDto {
@ApiPropertyOptional({
description: "기술 필터",
})
@IsOptional()
@IsArray()
@IsString({
each: true,
})
// 단일값 들어오면 배열로 변환
@Transform(({ value }) =>
Array.isArray(value) ? value : [value],
)
tech: string[];
}
단일 값일 경우
Get 요청의 Query값이 배열이 아닌 단일 값이라면 요청을 보내기 위해서 프론트에서https://api.test.com?tech=nest.js
이러한 형식으로 보내면 됩니다.
그렇다면 서버에서 받아야하는 값이 배열이라면 프론트에서는 어떻게 보내면 될까요?
배열인 경우
https://api.test.com?tech=nest.js&tech=next.js&tech=react
위와 같이 보내야할 값에 대한 키를 계속해서 선언하여 보내면 됩니다.
프론트에서 위와 같이 보내면 서버에서는 별다른 변환을 할 필요없이 배열로 받을 수 있습니다.
URLSearchParams
tech=nest.js&tech=next.js&tech=react
위 형태를 만들기 위한 유용한 Web API ,Node.js API가 있습니다. 즉, 클라이언트 사이드에서나 서버 사이드 둘 다에서 사용 가능합니다.
예시는 다음과 같습니다.
const params = new URLSearchParams();
const techArray = ["nest.js","next.js","react"]
techArray.forEach((tech) =>
params.append("tech", tech),
); // 여러 개의 tech 추가
const qs = params.toString() // => tech=nest.js&tech=next.js&tech=react
fetch(`https://api.test.com?${qs}`)
위와 같이 간편히 Query를 만들어 서버로 보내줄 수 있습니다.