首页 > 解决方案 > 通过 fetch(URL) 从谷歌表中获取数据但被 CORS 策略阻止

问题描述

我正在尝试从 Google Sheet 接收数据并且它正在工作,但目前获取失败并出现以下错误。

const url = `https://docs.google.com/spreadsheets/d/e/${id}/pub?gid=${gid}&single=true&output=csv`;
const result = await fetch(url);
const csvText = await result.text();

错误图像

标签: javascriptgoogle-sheets

解决方案


您可以使用代理服务器解决 CORS 问题。在这种情况下,您只需将 API 请求 URL 附加到代理服务提供商,例如,https://cors-anywhere.herokuapp.com/

var url = https://docs.google.com/spreadsheets/d/e/${id}/pub?gid=${gid}&single=true&output=csv;
var proxyUrl = https://cors-anywhere.herokuapp.com/${url};

fetch(proxyUrl)... //Make a request with this proxy url to navigate CORS issue

推荐阅读