无法从 React 应用程序获取 API
Posted
技术标签:
【中文标题】无法从 React 应用程序获取 API【英文标题】:Can't fetch API from React application 【发布时间】:2020-08-02 15:21:34 【问题描述】:我已经在 Google Cloud Function 中构建了 API。当我尝试直接获取 API 时发生 CORS 错误。虽然我加了Access-Control-Allow-Origin
,但是失败了。
错误:
'https://xxxxxxx.com' from origin 'http://localhost:3000' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求中不存在“Access-Control-Allow-Origin”标头资源。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。
const apiURL = 'https://xxxxxxx.com'
const headers = new Headers();
headers.set("Content-type", "application/json");
headers.set("Access-Control-Allow-Origin", "*");
const createRes = await fetch(
`$apiURL/testFetch`,
method: "POST",
headers: headers,
body: JSON.stringify(
test: "test"
),
);
【问题讨论】:
CORS 必须在服务器端而不是客户端启用。Access-Control-Allow-Origin
添加到响应头。有时浏览器不尊重*
,因此将准确的 URL 作为值可能会有所帮助。
【参考方案1】:
Access-Control-Allow-Origin 是一个 response 标头。它应该是您响应的一部分,而不是请求的一部分。请确保您的 API 返回相应的标头。
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
【讨论】:
以上是关于无法从 React 应用程序获取 API的主要内容,如果未能解决你的问题,请参考以下文章
在我的 React 应用程序中获取 api 数据时如何修复 CORS 错误?
如何从 Express API 获取数据并将其显示到 React 应用程序?