d3.js 从Google驱动器上传应用程序脚本中的csv文件被CORS策略阻止

qzlgjiam  于 2022-11-24  发布在  Go
关注(0)|答案(1)|浏览(169)

我想从谷歌表生成一个D3.js树。
在我下面的例子中,树是用csv生成的。所以,我已经用apps脚本在我的google驱动器上从google工作表生成了一个csv文件,现在,我试着像这个例子一样加载它:

<script src="https://d3js.org/d3.v4.js"></script>
<script>
d3.csv('https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/data_hierarchy_1level.csv', function(data) {console.log(data)})
</script>

在这里它工作正常,但当我试图从谷歌驱动器加载我自己的csv,我有这个代码:

<script src="https://d3js.org/d3.v4.js"></script>
<script>
d3.csv('https://drive.google.com/uc?id=1S9_KA87o_i7PjHILicXX21mlVeQc1jIA', function(data) {console.log(data)})
</script>

以下错误消息:
CORS策略已阻止从源“https://www.example.com”访问位于“”的XMLHttpRequestn-mvggraccraz7qqhyhidnzi7cecuqlcodyfxsjjq-0lu-script.googleusercontent.com:请求的资源上不存在“Access-Control-Allow-Origin”标头。
错误代码:11472获取https://drive.google.com/uc?id=1S9_KA87o_i7PjHILicXX21mlVeQc1jIA网络::错误失败303
我已经检查了2个文件。他们似乎是相同的。我不知道哪里是错误的。你能解释一下如何使用一个文件从驱动器一样,任何文件的网址?

xytpbqjk

xytpbqjk1#

在现阶段看来,使用webContentLink的端点如https://drive.google.com/uc?id=###&export=download时,会出现类似has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.的错误,为了避免这种情况,下面的模式如何?

模式1:

在这个模式中,使用了API密钥。当使用API密钥时,这个问题可以被消除。你可以在here看到如何检索API密钥。在你的URL中,它变成如下。

https://www.googleapis.com/drive/v3/files/{fileId}?alt=media&key={APIkey}

使用此URL时,它将变为以下脚本。

<script src="https://d3js.org/d3.v4.js"></script>
<script>
d3.csv('https://www.googleapis.com/drive/v3/files/{fileId}?alt=media&key={APIkey}', function(data) {console.log(data)})
</script>

模式2:

在这个模式中,没有使用API key,我看到你的问题时,注意到了In the exemple I followed, the tree is generated with a csv. So, I have generated with apps script a csv file on my google drive from a google sheet and now,由此我理解到你想使用从Spreadsheet中检索到的CSV数据,如果我理解正确的话,我认为你的目标可以直接使用Spreadsheet来实现,这个流程如下。

  • 将电子表格发布为网页。Ref
  • 这样,您就可以检索类似https://docs.google.com/spreadsheets/d/e/2PACX-###/pubhtml的URL。
  • 修改URL。
  • 请按如下方式修改上面检索到的URL。
https://docs.google.com/spreadsheets/d/e/2PACX-###/pub?output=csv
  • 在此URL中,将使用电子表格的第一个工作表。例如,当您要使用另一个工作表时,请使用工作表ID对其进行如下修改。
https://docs.google.com/spreadsheets/d/e/2PACX-###/pub?output=csv&gid={sheetId}

当此URL用于脚本时,它将变为如下所示。

<script src="https://d3js.org/d3.v4.js"></script>
<script>
d3.csv('https://docs.google.com/spreadsheets/d/e/2PACX-###/pub?output=csv', function(data) {console.log(data)})
</script>

相关问题