EtoC

Kakao map을 구현하며 겪은 에러 본문

ETC/Error

Kakao map을 구현하며 겪은 에러

게리드 2023. 9. 15. 12:21

구글맵스로 작업을 진행하다가 백에서 지도 어플리케이션을 바꿀 수 있는지 전화가왔다.

비용문제때문에 카카오맵스로 오케이하고 카카오맵을 불러와봤다.

그리고 또 다시 마주친 script unAthrized...

에러1 : ERR_ABORTED 401 (Unauthorized)

GET http://dapi.kakao.com/v2/maps/sdk.js?appkey=내토큰내용&libraries=services,clusterer,
drawing net::ERR_ABORTED 401 (Unauthorized)

.env 파일에 REACT_APP_JS_KEY 로 저장을 해두었고 복사해서 붙여넣기를 했는데 위와 같이 떴다.

시도1 : JS key 재발급

=> 여전히 같은 에러코드 발생

시도2 : 문자열 그대로 appkey= 에 넣어보기

unauthorized는 사라졌으나 키를 그대로 노출시켜야해서 안됨. => 일단 key가 맞는것은 확인.

시도3 : .env의 변수명 수정

혹시 정해진 이름이 있어서 사람들이 다 KAKAO_JS_KEY로 쓰는건가 싶어서 이름을 바꿔보았다.

그런데 REACT_APP_KAKAO_JS_KEY로 이름을 바꾸니까 에러가 사라졌다.

'뭐지..?이럴수가 있나?' 하고 다시 실행취소를 누르고 확인해보니

    <script
      type="text/javascript"
      src="//dapi.kakao.com/v2/maps/sdk.js?appkey=%REACT_APP_JS_KEY&libraries=services&autoload=false"
    ></script>

뒤에 %가 빠져서 그랬다.

아아..팀원이 "복붙좀 해요!"라던 환청이 들리는 느낌이다.


일단 js key 문제는 해겼했만 지도가 뜨지 않는다.

전에 했을때처럼 지도가 나중에 뜨는거도 아니고 아예 뜨지않았다.

이문제를 해결해보고싶어서 카카오맵 바꾸자고한것도 있는데 에러메세지가 없으니 참 어렵다.

대체 왜 이러는걸까?

//기존의 코드
import React, { useEffect, useRef } from 'react';
import styled from 'styled-components';

const { kakao } = window;

const KakaoMaps = () => {
  const mapContainer = useRef(null);

  useEffect(() => {
    navigator.geolocation.getCurrentPosition(position => {
      const { latitude, longitude } = position.coords;

      const script = document?.createElement('script');
      document.head.appendChild(script);

      script.onload = () => {
        kakao?.maps.load(() => {
          const container = mapContainer.current;
          const options = {
            center: new kakao.maps.LatLng(latitude, longitude),
            level: 3,
          };
          const map = new kakao.maps.Map(container, options);
        });
      };
    });
  }, []);

  return <MapContainer id="map" ref={mapContainer} />;
};

export default KakaoMaps;

const MapContainer = styled.div`
  width: 768px;
  height: 400px;
`;
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';

const KakaoMap = () => {
  const [map, setMap] = useState(null);
  const [marker, setMarker] = useState(null);

  useEffect(() => {
    window.kakao.maps.load(() => {
      const container = document.getElementById('map');
      const options = {
        center: new window.kakao.maps.LatLng(33.450701, 126.570667),
        level: 3,
      };

      setMap(new window.kakao.maps.Map(container, options));
      setMarker(new window.kakao.maps.Marker());
    });
  }, []);

  const getCurrentPosBtn = () => {
    navigator.geolocation.getCurrentPosition(
      getPosSuccess,
      () => alert('위치 정보를 가져올 수 없습니다.'),
      {
        enableHighAccuracy: true,
        maximumAge: 30000,
        timeout: 27000,
      },
    );
  };

  const getPosSuccess = pos => {
    var currentPos = new window.kakao.maps.LatLng(
      pos.coords.latitude,
      pos.coords.longitude,
    );

    map.panTo(currentPos);

    if (marker) {
      marker.setMap(null);
      marker.setPosition(currentPos);
      marker.setMap(map);
    }
  };

  return (
    <div>
      <MapContainer id="map" />
      <Button onClick={getCurrentPosBtn}>현재 위치 찾기</Button>
    </div>
  );
};

export default KakaoMap;

const MapContainer = styled.div`
  width: 768px;
  height: 400px;
`;

const Button = styled.div`
  cursor: pointer;
  background-color: #007bff;
  color: #fff;
  padding: 10px;
  border-radius: 5px;
  text-align: center;
  margin-top: 10px;
`;

에러 메세지가없어서 경고문도 한번 살펴봤다.

결론적으로는 코드의 동작과는 무관하다.

그래도 살펴봤으니 적어는 본다.

<!--warning-->
A parser-blocking, cross site (i.e. different eTLD+1) script, <URL>, is invoked via document.write. 
The network request for this script MAY be blocked by the browser in this or a future page load due to poor network connectivity. 
If blocked in this page load, it will be confirmed in a subsequent console message. 
See <URL> for more details.
<!--warning-->
sdk.js?appkey=a447ea6ce9e46dcbebd0f4fe9f22fc4a&libraries=services,clusterer,drawing:10 
A parser-blocking, cross site (i.e. different eTLD+1) script, http://t1.daumcdn.net/mapjsapi/js/main/4.4.14/kakao.js, is invoked via document.write. 
The network request for this script MAY be blocked by the browser in this or a future page load due to poor network connectivity. If blocked in this page load, it will be confirmed in a subsequent console message. 
See https://www.chromestatus.com/feature/5718547946799104 for more details.

parser-blocking은 카카오 도메인에 발급받은 쿠키를 기반으로 카카오의 서비스를 이용할ㄸ깨 쿠키가 브라우저의 쿠키 보안정책에 충족하지 못해서 발생하는 경고이다.

카카오의 답변으로는 지도 JS SDK는 쿠키를 기반으로 하는 동작이 없기때문에 지도 어플리케이션을 개발하는 입장에서는 무시해도 된다고 한다.

<!--verbose-->
kakaoMaps.jsx:10 [Violation] Only request geolocation information in response to a user gesture.
(anonymous) @ kakaoMaps.jsx:10
commitHookEffectListMount @ react-dom.development.js:23150
commitPassiveMountOnFiber @ react-dom.development.js:24926
commitPassiveMountEffects_complete @ react-dom.development.js:24891
commitPassiveMountEffects_begin @ react-dom.development.js:24878
commitPassiveMountEffects @ react-dom.development.js:24866
flushPassiveEffectsImpl @ react-dom.development.js:27039
flushPassiveEffects @ react-dom.development.js:26984
(anonymous) @ react-dom.development.js:26769
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533

이외에도 `document.write()`라는 경고문도 떴는데 이건 appkey에 내가 발급받은 코드를 그대로 복사 붙여넣기를해서 발생한거였다.

인터넷 속도가 느릴경우 script block이 발생할 수 있어 script를 document.write로 생성하는것은 가급적 자제하는게 좋다고 한다.

근데 지도가 로드되지않는다면 연관이 있을 수 도 있다고..