강디너의 개발 일지

Vue - google OAuth2 로그인 및 Youtube 연동 본문

Javascript/삽질

Vue - google OAuth2 로그인 및 Youtube 연동

강디너 2020. 1. 20. 20:15
728x90

Vue 에서 google OAuth 로그인을 위해서 mount 된 후 renderGoogleLoginButton 가 적용되게 했다.

하지만 mount 되는 속도보다 google API를 불러오는 속도가 느려서 오류가 나는 현상(gapi is not defined)이 자주 발생했다.

 

내생각 : Script Load -> mounted -> gapi render

하지만 : mounted -> gapi is not defined -> Script Load

 

mounted 가 더 빨라서 강제로 스크립트를 먼저 로드한 후 gapi 를 호출해야 했다.

<meta name="google-signin-client_id" content="945431733283-a4tf33jpvkabm0c1d56rqj96lu4i8iet.apps.googleusercontent.com">
<meta name="google-signin-fetch_basic_profile" content="email profile openid">
<meta name="google-signin-scope" content="https://www.googleapis.com/auth/youtube">
<script type="text/javascript">
function triggerGoogleLoaded() {
	window.dispatchEvent(new Event("google-loaded"));
}
</script>
<script src="https://apis.google.com/js/platform.js?onload=triggerGoogleLoaded" async defer></script>
<template>
  <div class="login_container">
      <div class="g-signin2" id="google-signin-btn"></div>
  </div>
</template>
mounted() {
        window.addEventListener("google-loaded", this.renderGoogleLoginButton);
},
methods: {
      renderGoogleLoginButton() {
        gapi.signin2.render("google-signin-btn", {
          'width': 240,
          'height': 50,
          longtitle: true,
          theme: 'dark',
          onsuccess: this.onSignIn,
        });
      },
      onSignIn (user) {
        const profile = user.getBasicProfile();
        const token = user.getAuthResponse().access_token;
        this.$store.commit('loginUser', profile);
        this.$store.commit('setToken', token);
        this.$router.push('/');
      },
},

 

강제로 스크립트가 로드가 완료되면 실행되는 트리거를 넣었고, 그 후에 renderGoogleLoginButton 이 실행되도록 설정하였다.

 

 

Youtube PlayList 에 접근하려면 OAuth 토큰이 필요하다.

 

Youtube PlayList 추가

export function addPlayList(name) {
	axios.defaults.headers['authorization'] = `Bearer ${Store.state.accessToken}`;
    const data = {
        snippet: {
            title: 'Deali_Music',
            description: `Dealicious ${name}`,
        },
    };
    return axios.post(`https://www.googleapis.com/youtube/v3/playlists?part=snippet`, data);
}

 

헤더에 authorization 을 넣어야하며 값으로 OAuth 토큰을 넣어야한다.

 

 

Google Cloud 설정

 

 

youtube 를 넣어주셔야합니다 !

커피한잔...
Comments