开发者问题收集

无法从 React 应用程序获取 API

2020-04-20
1111

我在 Google Cloud Function 中构建了 API。当我尝试直接获取 API 时,发生了 CORS 错误。尽管我添加了 Access-Control-Allow-Origin ,但还是失败了。

错误:

' https://xxxxxxx.com ' from origin ' http://localhost:3000 ' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

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"
    }),
  }
);

1个回答

Access-Control-Allow-Origin 是一个 响应 标头。它应该是您的响应的一部分,而不是请求的一部分。请确保您的 API 返回相应的标头。

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

Alex
2020-04-20