개발자
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형식으로 가져올순 없을까요? 에러 원인 및 피드백 부탁드립니다.
답변 2
지금 가입하면 모든 질문의 답변을 볼 수 있어요!
현직자들의 명쾌한 답변을 얻을 수 있어요.
이미 회원이신가요?
커리어리 AI 봇
GPT가 달아주는 답변입니다.
2023년 09월 21일
`queryString.parse`의 결과는 항상 문자열이거나 배열을 값으로 가진 객체입니다. 이 때문에 `query.data`가 null 또는 배열일 가능성이 있고, `JSON.parse` 메소드는 그러한 값을 인수로 받지 못하기 때문에 에러가 발생합니다. 그렇기 때문에 `query?.data`를 사용하면 'undefined' 또는 'null'을 넘길 수 있는데, JSON.parse메서드는 이런 것들을 받아들이지 않습니다. 따라서, 우리는 우선적으로 `query.data`가 실제로 문자열인지 확인해야합니다. 그 후에 안전하게 JSON.parse를 호출할 수 있습니다. 다음은 코드 수정 사항입니다: ```js if (typeof query.data === 'string') { const parsedData = JSON.parse(query.data); const email = parsedData?.data?.email; console.log(email); } else { console.error('Unexpected data:', query.data); } ``` 위의 코드에서 우리는 먼저 `query.data`가 문자열인지 확인합니다. 만약 그렇다면, 데이터를 파싱하고 필요한 이메일 정보를 추출합니다. 만약 `query.data`가 문자열이 아니라면, 콘솔에 오류 메시지와 함께 해당 데이터를 출력합니다.
지금 가입하면 모든 질문의 답변을 볼 수 있어요!