json-server에 axios.get요청시 파라미터가 적용되지 않음

LeeWonjin·2023년 2월 19일
0

문제해결

목록 보기
10/21

문제

아래와 같이 코드를 작성했다.

// json-server에 GET요청을 하는 스크립트
const params = {
	_limit: 2,
);
const getSomething = async (params) => {
  const { data } = await axios.get('https://localhost:5000/posts', params);
  console.log(data.length);
}

getSomething(params); // 4

// db.json
{
  "posts": [
    { "id": 1, "title": "title_1" },
    { "id": 2, "title": "title_2" },
    { "id": 3, "title": "title_3" },
    { "id": 4, "title": "title_4" }
  ]
}

params 파라미터 객체를 get요청시 같이 넘겼으나 파라미터가 적용되지 않는다.

GET /posts 304 8.002 ms - -
GET /posts/1 304 14.963 ms - -
GET /posts 304 21.135 ms - -
GET /posts/1 304 28.780 ms - -
GET /posts 304 19.110 ms - -
GET /posts/1 304 8.470 ms - -

해결

파라미터로 보낼 객체만 axios.get의 인수로 싣는게 아니다.
{ params : { 파라미터가 있는 객체 } } 를 실어보내야 한다.

// 이거 아니다
axios.get('https://localhost:5000/posts', params);

// 이거 맞다
axios.get('https://localhost:5000/posts', { params });
axios.get('https://localhost:5000/posts', { params : params });
profile
노는게 제일 좋습니다.

0개의 댓글