• 카테고리

    질문 & 답변
  • 세부 분야

    모바일 앱 개발

  • 해결 여부

    해결됨

카카오 주소 검색 기능 401 에러

24.05.13 00:21 작성 조회수 146

1

 LOG  a {"latitude": 37.550165, "longitude": 127.12752} LOG  [AxiosError: Request failed with status code 401강의영상 잘 따라하고, REST API KEY까지 제대로 입력했는데, 위와 같은 에러가 발생합니다.import React from 'react'; import {StyleSheet, TextInput, TextInputProps, View} from 'react-native'; import Ionicons from 'react-native-vector-icons/Ionicons'; import {colors} from '@/constants'; interface SearchInputProps extends TextInputProps { onSubmit: () => void; } function SearchInput({onSubmit, ...props}: SearchInputProps) { return ( <View style={styles.container}> <TextInput style={styles.input} autoCapitalize="none" placeholderTextColor={colors.GRAY_500} returnKeyType="search" onSubmitEditing={onSubmit} clearButtonMode="while-editing" {...props} /> <Ionicons name={'search'} color={colors.GRAY_700} size={20} onPress={onSubmit} /> </View> ); } const styles = StyleSheet.create({ container: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', borderWidth: 1, borderColor: colors.GRAY_200, paddingVertical: 8, paddingHorizontal: 10, borderRadius: 5, }, input: { flex: 1, fontSize: 16, paddingVertical: 0, paddingLeft: 0, color: colors.BLACK, }, }); export default SearchInput; import axios from 'axios'; import {useEffect, useState} from 'react'; import Config from 'react-native-config'; import {LatLng} from 'react-native-maps'; type Meta = { total_count: number; pageable_count: number; is_end: boolean; same_name: { region: string[]; keyword: string; selected_region: string; }; }; export type RegionInfo = { address_name: string; category_group_code: string; category_group_name: string; category_name: string; distance: string; id: string; phone: string; place_name: string; place_url: string; road_address_name: string; x: string; y: string; }; type RegionResponse = { meta: Meta; documents: RegionInfo[]; }; function useSearchLocation(keyword: string, location: LatLng) { const [regionInfo, setRegionInfo] = useState<RegionInfo[]>([]); const [pageParam, setPageParam] = useState(1); console.log(keyword, location); useEffect(() => { (async () => { try { const {data} = await axios.get( `https://dapi.kakao.com/v2/local/search/address.json?query=${keyword}&y=${location.latitude}&x=${location.longitude}&page=${pageParam}`, { headers: { Authorization: `KakaoAK ${Config.KAKAO_REST_API_KEY}`, }, }, ); console.log('data', data); } catch (error) { console.log(error); } })(); }, [keyword, location]); return {regionInfo}; } export default useSearchLocation; GOOGLE_API_KEY=키내용들 KAKAO_REST_API_KEY=키내용들
어떤 부분이 잘못되어서 401 에러가 발생하는지 알고싶습니다.

답변 3

·

답변을 작성해보세요.

0

장경찬님의 프로필

장경찬

2024.05.13

저도 같은 증상이었는데

IOS 빌드 다시하니 해결 됐습니다!

0

김용민님의 프로필

김용민

질문자

2024.05.13

https://github.com/dydals3440/MatZip

깃허브 주소 같이 전달드립니다!

0

김용민님의 프로필

김용민

질문자

2024.05.13

import SearchInput from '@/components/common/SearchInput';
import useSearchLocation from '@/hooks/useSearchLocation';
import useUserLocation from '@/hooks/useUserLocation';
import React, {useState} from 'react';
import {Keyboard, StyleSheet, View} from 'react-native';

const SearchLocationScreen = () => {
  const [keyword, setKeyword] = useState<string>('');
  const {userLocation} = useUserLocation();
  const {regionInfo} = useSearchLocation(keyword, userLocation);

  const handleChangeKeyword = (text: string) => {
    setKeyword(text);
  };

  return (
    <View style={styles.container}>
      <SearchInput
        autoFocus
        value={keyword}
        onChangeText={handleChangeKeyword}
        placeholder="검색할 장소를 입력하세요."
        onSubmit={() => Keyboard.dismiss()}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
  },
});

export default SearchLocationScreen;
import axios from 'axios';
import {useEffect, useState} from 'react';
import Config from 'react-native-config';
import {LatLng} from 'react-native-maps';

type Meta = {
  total_count: number;
  pageable_count: number;
  is_end: boolean;
  same_name: {
    region: string[];
    keyword: string;
    selected_region: string;
  };
};

export type RegionInfo = {
  address_name: string;
  category_group_code: string;
  category_group_name: string;
  category_name: string;
  distance: string;
  id: string;
  phone: string;
  place_name: string;
  place_url: string;
  road_address_name: string;
  x: string;
  y: string;
};

type RegionResponse = {
  meta: Meta;
  documents: RegionInfo[];
};

function useSearchLocation(keyword: string, location: LatLng) {
  const [regionInfo, setRegionInfo] = useState<RegionInfo[]>([]);
  const [pageParam, setPageParam] = useState(1);
  console.log(keyword, location);
  useEffect(() => {
    (async () => {
      try {
        const {data} = await axios.get(
          `https://dapi.kakao.com/v2/local/search/address.json?query=${keyword}&y=${location.latitude}&x=${location.longitude}&page=${pageParam}`,
          {
            headers: {
              Authorization: `KakaoAK ${Config.KAKAO_REST_API_KEY}`,
            },
          },
        );
        console.log('data', data);
      } catch (error) {
        console.log(error);
      }
    })();
  }, [keyword, location]);

  return {regionInfo};
}

export default useSearchLocation;
GOOGLE_API_KEY=키값들
KAKAO_REST_API_KEY=키값들
김용민님의 프로필

김용민

질문자

2024.05.13

자꾸 인프런 문제인지 모르겠는데, 코드블럭으로 올려도 게시후에 리다이렉 하면, 저렇게 올라가지네요, 아래에 다시 코드블럭 형태로 올렸습니다!

Kyo님의 프로필

Kyo

지식공유자

2024.05.13

kakao api를 호출할때 401에러가 발생하나요? 지금 Config.KAKAO_REST_APIKEY는 잘 찍히는 상태인가요?

김용민님의 프로필

김용민

질문자

2024.05.13

계속 undefined가 출력됩니다!! 맞게 변수명을 입력했는데도 말이죠, GOOGLE_API_KEY는 발 불러와지는데 KAKAO_REST_API_KEY는 잘 불러와지지 않습니다 ㅠ

Kyo님의 프로필

Kyo

지식공유자

2024.05.13

restapi키가 뜨지않으신다면 환경변수 설정이 제대로 되지 않은것이 문제네요. 그부분을 보셔야할것같습니다!

김용민님의 프로필

김용민

질문자

2024.05.13

GOOGLE_API_KEY=A123123123123123123
KAKAO_API_KEY=123B123123123123BBB
import axios from 'axios';
import {useEffect, useState} from 'react';
import {LatLng} from 'react-native-maps';
import Config from 'react-native-config';

type Meta = {
  total_count: number;
  pageable_count: number;
  is_end: boolean;
  same_name: {
    region: string[];
    keyword: string;
    selected_region: string;
  };
};

export type RegionInfo = {
  address_name: string;
  category_group_code: string;
  category_group_name: string;
  category_name: string;
  distance: string;
  id: string;
  phone: string;
  place_name: string;
  place_url: string;
  road_address_name: string;
  x: string;
  y: string;
};

type RegionResponse = {
  meta: Meta;
  documents: RegionInfo[];
};

function useSearchLocation(keyword: string, location: LatLng) {
  const [regionInfo, setRegionInfo] = useState<RegionInfo[]>([]);
  const [pageParam, setPageParam] = useState(1);
  console.log('gd', Config.KAKAO_REST_API_KEY);

  useEffect(() => {
    (async () => {
      try {
        const {data} = await axios.get<RegionResponse>(
          `https://dapi.kakao.com/v2/local/search/keyword.json?query=${keyword}&y=${location.latitude}&x=${location.longitude}&page=${pageParam}`,
          {
            headers: {
              Authorization: `KakaoAK ${Config.KAKAO_REST_API_KEY}`,
            },
          },
        );
        console.log('data', data);
      } catch (error) {
        console.log(error);
      }
    })();
  }, [keyword, location]);

  return {regionInfo};
}

export default useSearchLocation;

제대로 불러와 지기는 하는데, 401 에러가 발생합니다!! 혹시 simulator상에서 조금 더 자세하게 디버깅 할 수 있는 방법이 있나요? 웹 개발시 네트워크탭처럼요!

Kyo님의 프로필

Kyo

지식공유자

2024.05.13

많이 사용하는 것으로는 Flipper가 있습니다. https://fbflipper.com/docs/features/react-native/

그런데 환경변수가 콘솔에 둘다 찍히거나 둘다 안찍혀야할텐데 GOOGLE_API_KEY는 불러와지는데 KAKAO_REST_API_KEY는 찍히지 않는다는것이 이상한데요. 오타가 있는건 아닐까요?

코드중에 KAKAO_API_KEY로 올리신것이 있고 KAKAO_REST_API_KEY 로 올리신것이 있는데 확인부탁드려요!