首页 > 解决方案 > 使用 gapi.client.request 访问 Drive thumbnailLink 给出 404

问题描述

我目前正在开发一个 React 应用程序,它应该从用户的 Google Drive 加载一组(非公开)文件并使用 CSSbackground-image: url(...)属性显示缩略图。我可以使用 GapiFiles:get方法加载所有文件元数据,并使用gapi.client.setToken. 我希望按如下方式加载缩略图:

function CollectionArtifact(props){
     const [thumbnail, setThumbnail] = useState(null);
     
     async function loadThumbnail(){
          try {
               const res = await window.gapi.client.request(props.artifact.thumbnailLink);
               const data = await res.blob();
               const localURL = URL.createObjectUrl(data);
               setThumbnail(localURL);
          catch(e){ console.log('Failed to load thumbnail', e); }
     }

     useEffect(() => {
          if(props.apisLoaded){
               loadThumbnail();
          }
     }, [props.apisLoaded]);

     return (
          ...
          <div style={{backgroundImage: `url(${thumbnail})`}}>
               ...
          </div>
          ...
     );
}

客户端在包装组件中初始化,如下所示:

window.gapi.load('client:auth2', () => {
     window.gapi.client.init({
          apiKey: developerKey,
          clientId: clientId,
          scope: 'https://www.googleapis.com/auth/drive'
     }).then(() => {
          window.gapi.client.load('drive', 'v3', () => {
               if(props.onGapisLoad) props.onGapisLoad();
               setInitialized(true);
          });
     });
});

但是,window.gapi.client.request调用给出了Failed to load resource: the server responded with a status of 404,而实际给出此错误的 URL 是代理请求https://docs.google.com/static/proxy.html?usegapi=1&...。使用fetch也不起作用,因为它会产生 CORS 错误。同时,如果我在登录到正确的 Google 帐户(并且没有其他帐户)时尝试thumbnailLink在浏览器中访问,我可以毫无问题地看到图像。

通过授权请求加载缩略图的正确方法是什么?我已经看到其他建议生成 PDF 并使用它来创建公共缩略图的答案,但我想避免在用户的驱动器中创建额外的文件或使文件数据可公开访问。而且由于图像可以直接从浏览器加载,我认为有一种方法可以使用授权客户端访问它。

标签: reactjsgoogle-apigoogle-drive-apigoogle-oauthgoogle-api-js-client

解决方案


推荐阅读