首页 > 解决方案 > 无法从谷歌日历获取事件数据

问题描述

在组件 App.js 中,我尝试使用 google auth 和 firebase 登录并获取数据并将其添加到谷歌日历,但我在获取数据时出错

  const SyncroWidthGoogle = (e) => {
    e.preventDefault();
    window.gapi.load("client:auth2", () => {
      window.gapi.client.init({
        apiKey: "api",
        clientId:
          "id.apps.googleusercontent.com",
        discoveryDocs: [
          "https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest",
        ],
        scope: "https://www.googleapis.com/auth/calendar",
      });

      window.gapi.client.load("calendar", "v3", () => {
        console.log("loaded calrendar");
      });
      async function login() {
        const googleAuth = window.gapi.auth2.getAuthInstance();
        const googleUser = await googleAuth.signIn();

        const token = googleUser.getAuthResponse().id_token;
        console.log(googleUser, token);

        const credential = firebase.auth.GoogleAuthProvider.credential(token);
        
        const googleProvider = new firebase.auth.GoogleAuthProvider.credential(
          token
        );
        const signInWithGoogle = async () => {
          firebase
            .auth()
            .signInWithPopup(googleProvider)
            .then((res) => {
              console.log(res);
            })
            .catch((error) => {
              console.log(error.message);
            });
        };
        signInWithGoogle();
      }
      login();
    });
  };

  const getEvents = (e) => {
    e.preventDefault();
    window.gapi.client.load("calendar", "v3", async () => {
      const events = await window.gapi.client.calendar.events.list({
        calendarId: "primary",
        showDeleted: false,
        maxResults: 10,
        singleEvents: true,
      });

      console.log(events);
    });
    getEvents();
  };

并返回

<button onClick={(e) => SyncroWidthGoogle(e)}>SYNCRO</button>
      <button onClick={(e) => getEvents(e)}>events</button>

我成功登录并拥有控制台令牌和响应,但是当我单击获取事件时出现错误 window.gapi.client is undefined

标签: javascriptreactjs

解决方案


推荐阅读