从 React 应用程序向 Google Drive API 发送 POST 请求时如何绕过 CORS 错误?

Posted

技术标签:

【中文标题】从 React 应用程序向 Google Drive API 发送 POST 请求时如何绕过 CORS 错误?【英文标题】:How to bypass CORS error when sending POST request to Google Drive API from react application? 【发布时间】:2019-12-14 16:14:06 【问题描述】:

我是网络开发新手,当我尝试将文件上传的 POST 请求从我的 React 应用程序发送到我的 Google Drive 帐户时,我无法绕过 CORS。这是我在上传文件回调函数中所做的:

function uploadFile(file) 
    var metadata = 
        'name': 'Test File', // Filename at Google Drive
        'mimeType': file.type, // mimeType at Google Drive
    ;

    var accessToken = (copied generated access token from OAUTH playground)
    var form = new FormData();
    form.append('metadata', new Blob([JSON.stringify(metadata)], type: 'application/json'));
    form.append('file', file);

    var xhr = new XMLHttpRequest();
    xhr.open('post', 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id');
    xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
    xhr.responseType = 'json';
    xhr.onload = () => 
        console.log(xhr.response.id); // Retrieve uploaded file ID.
    ;
    xhr.send(form);

我正在关注https://gist.github.com/tanaikech/bd53b366aedef70e35a35f449c51eced 的示例脚本,当我复制第一个示例脚本时,一切似乎都运行良好。但是,当我从桌面上传文件,然后通过我的应用上传时,我会收到 503 错误以及:

"... 已被 CORS 策略阻止。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin ... 不允许访问。"

我一直在检查 Stack Overflow 上提出的一些类似问题,似乎最好的方法是让托管资源的服务器启用 CORS。但在这种情况下,我向 Google 的 API 发出请求,那么处理这个问题的最佳方法是什么?特别是客户端解决方案?任何帮助表示赞赏

【问题讨论】:

如果您使用create-react-app,则无需手动设置网络服务器。 React 脚本支持开箱即用的代理服务器,请在此处查看此答案以了解如何配置它:***.com/questions/51128176/… 【参考方案1】:

使用代理 https://cors-anywhere.herokuapp.com

所以你的网址将是 https://cors-anywhere.herokuapp.com/https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id'

在 Api Url 之前连接此 URL,否则在调用时将其发送到标头中

Access-Control-Allow-Origin:'*'

【讨论】:

感谢您的回答!但是,我认为这两种方法都不起作用,因为 cors-anywhere 代理基本上将 Access-Control-Allow-Origin: '*' 添加到响应标头中,但这仍然会引发此错误:Cannot use wildcard in Access -Control-Allow-Origin 当凭证标志为真并要求您在响应中设置来源以匹配请求这是 b/c 凭证标志必须在 Google Drive 的 API 中为真。此外,如果你使用 Axios,代理不支持 withCredentials=true

以上是关于从 React 应用程序向 Google Drive API 发送 POST 请求时如何绕过 CORS 错误?的主要内容,如果未能解决你的问题,请参考以下文章

从 React 应用程序向 Rocket 后端发送 POST 请求时出错返回失败

从 Google 地图向带有地理信息的 Android 应用发送 Intent

react-router如何从客户端向服务器中间件发送请求?

通过代码从 Apache Beam 应用程序向 Google Cloud 进行身份验证

有没有办法从 Google appengine 标准向网络浏览器发送推送通知? [关闭]

如何使用 react-google-maps 通过单击在地图上添加标记?