guruahn / vue3-google-oauth2-front-sample

vue3환경에서의 vue-google-oauth2 테스트.
MIT License
20 stars 17 forks source link

Add an API call to the example #2

Open pgoldtho opened 3 years ago

pgoldtho commented 3 years ago

It would be nice if the example included some sample code showing an API call for an authenticated user. It took me a while to figure out how to do this. Here's what I came up with. Not sure if its best practice but seems to work.

  data(){
    return {
      user: '',
      id_token: ''
    }
  },

  methods: {
    async handleClickSignIn(){
      try {
        const googleUser = await this.$gAuth.signIn();
        if (!googleUser) {
          return null;
        }
        console.log("googleUser", googleUser);
        this.user = googleUser.getBasicProfile().getEmail();
        this.id_token = this.$gAuth.instance.currentUser.get().getAuthResponse().id_token;
      } catch (error) {
        //on fail do something
        console.error(error);
        return null;
      }
    },

  async makeApiCall(){
      const res = await fetch(SOME-URL, {
        headers: {
          Authorization: `Bearer ${this.id_token}`
        }
      });

   // process response

}