从 google oauth2 Web 客户端 requestAccessToken 函数获取 c.trim 错误

Abd*_*man 4 oauth-2.0 google-oauth reactjs

我正在使用 google Oauth2 客户端脚本,但在“requestAccessToken”函数中出现了 2 个错误。见下图

在这里,我动态加载“https://accounts.google.com/gsi/client”脚本,加载后我使用 initTokenClient 函数创建 tokenClient。

当用户单击按钮时,我检查令牌是否已可用,如果没有,则我将发送对 google auth popup tokenClient.current.requestAccessToken({ Prompt: 'consent' }); 的请求 但是这个requestAccessToken函数给我一个名为c.trim() 的错误,它不是一个 funciton。据我发现它来自该函数的内部实现

我还在同一个地方收到另一个 CORS 错误。

重现链接:https://codesandbox.io/s/nostalgic-ives-wngw3v ?file=/src/Picker.jsx

错误图像

import React, { useEffect, useRef, useState } from 'react';
import loadScript from 'load-script';

const GOOGLE_INDENTITY_URL = 'https://accounts.google.com/gsi/client';

const clientId = '865996907937-t2ca9nu95hv87f204t11gikb2rqm3s4v.apps.googleusercontent.com';
const scope = ['https://www.googleapis.com/auth/drive.readonly'];

let scriptLoadingStarted = false;

export default function TryPicker() {
  const tokenClient = useRef();
  const isGoogleAuthReady = () => {
    return !!window.google?.accounts?.oauth2;
  };

  const doAuth = () => {
    console.log('yea', tokenClient.current, tokenClient.current.requestAccessToken);
    // // Use Google Identity Services to request an access token
    tokenClient.current.requestAccessToken({ prompt: 'consent' });
  };

  const onChoose = () => {
    if (!isGoogleAuthReady()) {
      return null;
    }

    doAuth();

    return undefined;
  };

  const onAuthLoad = () => {
    tokenClient.current = window.google.accounts.oauth2.initTokenClient({
      client_id: clientId,
      scope,
      callback: async response => {
        if (response.error !== undefined) {
          throw response;
        }

        console.log(response);
      },
    });
  };

  useEffect(() => {
    if (isGoogleAuthReady()) {
      // google api is already exists
      // init immediately
      onAuthLoad();
    } else if (!scriptLoadingStarted) {
      // load google api and the init
      scriptLoadingStarted = true;
      loadScript(GOOGLE_INDENTITY_URL, onAuthLoad);
    } else {
      // is loading
    }
  });

  return (
    <div>
      <button className="text-darker" onClick={onChoose} type="button">
        Get access token
      </button>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

小智 5

正如 yash 所提到的,这可能是因为您正在使用数组。这就是如何将其用于多个范围。

scope: 'https://www.googleapis.com/auth/user.birthday.read \
     https://www.googleapis.com/auth/profile.agerange.read \
     https://www.googleapis.com/auth/user.gender.read',
```
Run Code Online (Sandbox Code Playgroud)