首页 > 解决方案 > 具有正确标头的 localhost 事件上的 CORS 错误

问题描述

我的服务在响应中有以下标头:

access-control-allow-origin: *
access-control-allow-headers: *
access-control-allow-methods: *

我的 cloudflare 工作者

addEventListener("fetch", (event) => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  const headers = new Headers({
    "Content-Type": "application/json",
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Headers": "*",
    "Access-Control-Allow-Methods": "*",
    "Access-Control-Max-Age": "-1",
  });

  return new Response(
    JSON.stringify({
      network_address: request.headers.get("CF-Connecting-IP"),
    }),
    { headers: headers, status: 200 }
  );
}

我们可以使用 cURL 检查

curl -s -D - -o /dev/null https://example.com

HTTP/2 200
date: Thu, 02 Sep 2021 13:20:55 GMT
content-type: application/json
content-length: 36
access-control-allow-origin: *
access-control-allow-headers: *
access-control-allow-methods: *
access-control-max-age: -1
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
report-to: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=HERU%2BxkJuLdgGnre4HxDofQDXnCZGbEsX4RVTaL%2FjmO%2FE0iIRY7UGEYvkBpL85g%2F7o3V4ZdbpNma48SpLg%2BZ%2FFnW4hIf%2F3tpNCfA4EocZCtYCOdNAsEooxBAww%3D%3D"}],"group":"cf-nel","max_age":604800}
nel: {"success_fraction":0,"report_to":"cf-nel","max_age":604800}
server: cloudflare
cf-ray: 688709d64bdc51f8-GRU
alt-svc: h3-27=":443"; ma=86400, h3-28=":443"; ma=86400, h3-29=":443"; ma=86400, h3=":443"; ma=86400

我的代码:

const response = await fetch(`//example.com/?_=${Math.floor(Date.now() / 1000)}`)

const { network_address } = await response.json()

不幸的是,在localhost:3000浏览器上由于 CORS 无法执行请求,见下图:

我需要做什么才能在本地主机上允许 CORS?

标签: expressgoogle-chromehttpcorscloudflare-workers

解决方案


当您尝试通过不允许 CORS 访问的客户端访问第三方 API 时,通常会发生 CORS 错误。

我的建议是通过服务器端访问这些 API,这意味着您将创建和访问本地 API,并且该 API 调用第三方 API。这样您就可以绕过 CORS 错误并且也很安全。此建议的缺点是当您没有服务器端设置时,您需要创建一个。


推荐阅读