본문 바로가기

프론트엔드 공부/react

react kakao login api 리액트 카카오 로그인 api 코드

tailwindcss사용한 간단한 로그인 로그아웃 카카오api 구현 입니다.

하단 index.html파일 javascript 키만 본인 것으로 변경하시면 잘 되리라 생각합니다.

//KaKaoLogin.js
import React from "react";
const { Kakao } = window;
const KaKaoLogin = () => {
  //카카오로그인
  function kakaoLogin() {
    Kakao.Auth.login({
      success: function (response) {
        Kakao.API.request({
          url: "/v2/user/me",
          success: function (response) {
            console.log(response);
          },
          fail: function (error) {
            console.log(error);
          },
        });
      },
      fail: function (error) {
        console.log(error);
      },
    });
  }
  //카카오로그아웃
  function kakaoLogout() {
    if (Kakao.Auth.getAccessToken()) {
      Kakao.API.request({
        url: "/v1/user/unlink",
        success: function (response) {
          console.log(response);
        },
        fail: function (error) {
          console.log(error);
        },
      });
      Kakao.Auth.setAccessToken(undefined);
    }
  }
  return (
    <div>
      <button className="bg-yellow-300" onClick={kakaoLogin}>
        로그인
      </button>
      <button className="bg-red-500" onClick={kakaoLogout}>
        로그아웃
      </button>
    </div>
  );
};

export default KaKaoLogin;
//index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />

    <!-- OAuth: Kakao -->
    <script src="https://developers.kakao.com/sdk/js/kakao.js"></script>
    <script>
      Kakao.init("******jskey*****");
    </script>

    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

    <title>title</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

만약 !!

이런 오류가 난다면

{"error":"unauthorized","error_description":"unauthorized - unregistered website domain"}

카카오개발자 페이지에서 내어플리케이션 > 앱설정> 플랫폼의 사이트도메인이 현재 열린 로컬호스트 포트와 동일한지 확인해보아야한다.