[Typescript] MSW axios get params 에러핸들링

hyo·2023년 1월 25일
2
post-thumbnail

Typescript MSW axios get요청시 params가 빈객체로 나온다....

문제

Typescript를 사용하며 axios get 요청에 params를 넣어 보내면
MSW에서 req.params가 빈객체로 나온다...

// SignUp.tsx
const onClickBtn = (): void => {
  axios.get('/members/verify', {
    params: {
      email:'abcd@naver.com', 
      password: '12345'
    })
}
// MSW handler.ts
interface UserInfo {
  email?: string;
  password?: string;
  nickName?: string;
}
export const handlers = [
  rest.get<UserInfo>('/members/verify', (req,res,ctx) => {
    console.log(req.params) //  {}  빈 객체 나옴
  })
]

해결하기위한 몇가지의 시도!

  • Get 요청에 데이터를 전달할때 MSW서버에서 res.body로 받아오면 받아올 줄 알았다. 하지만 undefined

  • Get 요청에 데이터를 params : {데이터} 로 넣어서 보내면 될 줄 알았다. 하지만 req.params = {} ... 빈객체...

  • AxiosInstance를 extends 하여 CustomInstance를 만들어 typescript의 type을 지정하고 속성을 넣어주려했으나 실패..

해결

URLSearchParams

rest.get('/members/verify', (req,res,ctx) => {
  const searchParam = new URLSearchParams(req.url.searchParams);
  console.log(searchParam.get('email')); // 'abcd@naver.com' 값이 불러와짐!
})

URLSearchParams 를 사용해 변수에 담고 get 을 사용해 key값을 입력해주면 해당 key의 value를 불러오는 것이 가능하다.

profile
개발 재밌다

0개의 댓글