Lennon FE

[카카오 OAuth2] 웹에서 카카오 로그인을 구현해보자 (2) 본문

✏️ Development/kakao OAuth2

[카카오 OAuth2] 웹에서 카카오 로그인을 구현해보자 (2)

Lennon 2022. 2. 11. 19:52
728x90
반응형

https://parkparkpark.tistory.com/111

 

[카카오 OAuth2] 웹에서 카카오 로그인을 구현해보자 (1)

SNS 로그인? 요즘 대부분의 서비스는 sns 로그인이 필수적으로 들어가는 것 같다. 아마도 사용자 경험 측면에서 편리하고 유용하게 서비스를 이용할 수 있도록 하기 위해 그런 것이 아닐까?라는

parkparkpark.tistory.com

 

로그인을 구현하고 로그인 후 이동되는 main.html에 프로필 정보를 띄어보자.

// profile.js

class Profile {
  constructor(data) {
    this.name = data.properties.nickname;
    this.img = data.properties.profile_image;
  }

  printProfile() {
    const profile = document.createElement('div');

    const profile_nickname = document.createElement('p');
    const profile_img = document.createElement('img');

    profile_nickname.id = 'profile-name';
    profile_img.id = 'profile-img';
    profile_img.src = this.img;

    const resultProfileNickname = document.createTextNode(
      `${this.name}님 환영합니다`
    );
    profile_nickname.append(resultProfileNickname);

    profile.appendChild(profile_img);
    profile.appendChild(profile_nickname);

    document.querySelector('#app').appendChild(profile);
    }
  }
  
  export default Profile;

constructor에서 프로필 정보인 data를 인수로 받고, 카카오 정보의 내장되어있는 data.properties.nickname와 image를 가져온다.

그 후 javascript로 html을 핸들링해 이름과 이미지 값을 추가하자!

(필자는 이거뿐만 아니라 다양한 걸 간단하게 쓰기위해 class를 사용했다. 아니면 그냥 함수로 선언해도 무방하다)

//index.js

import Profile from './profile.js';

const data = await window.Kakao.API.request({
  url: '/v2/user/me',
});

const $profile = new Profile(data);
$profile.printProfile();

index.js는 이렇게 구성하자!

data는 카카오API에 들어있는 내 정보를 가져와서 Profile를 불러올 때 인자로 넣어주면 된다.

이미 전 포스팅에 html은 작성했으니 프로필사진과 이름 정보가 화면이 제대로 출력되는 지 확인해보도록 하자.

잘 출력되는 걸 확인할 수 있다. 위 profile.js에서 id값을 각각 추가했으니, css를 조정하여 원하는 위치에 넣어보도록하자. 

myPage.html을 만들어서 해당 파일에 띄워도 무방하다.

 

728x90
반응형
Comments