为什么具有相同域的重定向URL会遇到CORS问题?

时间:2019-03-26 03:38:22

标签: node.js redirect cors fetch charles-proxy

情况有点复杂。我使用http服务器将本地代码托管在localhost:8080。然后,我使用Charles将在线URL(example.online.com/index.html)映射到我的本地URL(localhost:8080 / index.html)以共享cookie。然后,我在本地主机:9963启动了本地节点服务器作为模拟服务器,该模拟服务器已实现了CORS设置。我使用本地代码中的Fetch Api向localhost:9963 / api / list发出了请求,因此该请求使用了带有cors的模拟数据来响应。有时,我不希望模拟服务器响应模拟数据。相反,模拟服务器使用307将请求(localhost:9963 / api / list)重定向到了在线api(example.online.com/api/list)。问题在于,当浏览器遵循重定向时,会出现CORS问题发生了。我的困惑是,为什么当重定向的URL http://example.online.com/api/listhttp://example.online.com/index.html位于同一域时会发生CORS。

错误是(原始URL被示例URL替换):

从原点“空”获取对“ http://example.online.com/api/list”(从“ http://localhost:9963/api/list”重定向)的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:否“ Access-Control-Allow-Origin”标头存在于请求的资源上。如果不透明的响应满足您的需求,请将请求的模式设置为“ no-cors”以在禁用CORS的情况下获取资源。

获取代码为:

  const url = `http://localhost:9963/api/list`;
  const method = 'POST';
  const headers = {
    "Content-Type": `application/json`,
    "Accept": `application/json`
  };
  const body = JSON.stringify(req);
  const credentials = 'include';
  const mode = 'cors';
  return fetch(url, {
    method,
    headers,
    body,
    credentials,
    mode
  })

重定向代码是(使用koa2):

  const r_url = 'http://example.online.com/api/list';
  ctx.status = 307;
  ctx.redirect(r_url);

0 个答案:

没有答案
相关问题