개발자

queryString에 관하여

2023년 09월 21일조회 94

http://test.com?auth=true&data={"endPoint":"/auth","data":"{"email":"test@test.com","name":"홍길동"}"} const query = queryString.parse(window.location.search); query 사용해서 data안에 객체로 되어있는 정보들 중 data안에 email 정보(test@test.com)을 뽑아오려면 어떻게해야하나요? const query = queryString.parse(window.location.search); console.log('query.data',query.data) //query.data까지는 뽑히는데 console.log('query.data.data', query.data.data) //undefined 그래서 const parsedData = JSON.parse(query?.data); //JSON형식 const email = parsedData.data.email; //test@test.com 정보가 뽑혔어요! 하지만 query?.data에서 에러가 납니다. **error 메세지 No overload matches this call. Overload 1 of 2, '(text: string, reviver?: ((this: any, key: string, value: any) => any) | undefined): unknown', gave the following error. Argument of type 'string | (string | null)[] | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'. Overload 2 of 2, '(text: string, reviver?: ((this: any, key: string, value: any) => any) | undefined): any', gave the following error. Argument of type 'string | (string | null)[] | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'. query?.data에서 위와 같은 에러가 납니다.. query?.data의 type은 JSON형식 아니고 string입니다. console.log(query?.data) // {"endpoint":"/auth","data":{"email":"test@test.com","name":"홍길동"}} string에서 email을 뽑아야할까요?.. JSON형식으로 가져올순 없을까요? 에러 원인 및 피드백 부탁드립니다.

이 질문이 도움이 되었나요?
'추천해요' 버튼을 누르면 좋은 질문이 더 많은 사람에게 노출될 수 있어요. '보충이 필요해요' 버튼을 누르면 질문자에게 질문 내용 보충을 요청하는 알림이 가요.
profile picture
익명님의 질문

답변 2

김도열님의 프로필 사진

이런 식이면 될 것 같습니다.

1
2
3
4
5
const parsedQuery = queryString.parse(url);
const dataObject = JSON.parse(parsedQuery.data);
const email = dataObject.data.email;

console.log(email);
profile picture

익명

작성자

2023년 09월 23일

타입 정의로 해결했습니다.

1
const parsedData:any = JSON.parse(query?.data as string);

지금 가입하면 모든 질문의 답변을 볼 수 있어요!

현직자들의 명쾌한 답변을 얻을 수 있어요.

또는

이미 회원이신가요?

목록으로
키워드로 질문 모아보기

실무, 커리어 고민이 있다면

새로운 질문 올리기

지금 가입하면 모든 질문의 답변을 볼 수 있어요!