Cross-Origin客户端资源共享怎么办?

How to do Cross-Origin Resource sharing from client?

我知道这个问题的标题没有意义,因为客户不分享任何东西,它请求。但是,假设我想写一个 RSS reader 作为练习。所以我会将所有数据存储在客户端的 IndexedDB(或本地存储)中,并且我想获取一些流。所以我做例如

fetch('https://bunyk.wordpress.com/feed/')

但是 wordpress.com 不在我的控制范围内,它给我错误

No 'Access-Control-Allow-Origin' header is present on the requested resource.

我可以通过使用 {mode: 'no-cors'} 来避免该错误,但那样我也无法获取内容。

有什么办法让它工作,或者我需要编写和托管一些瘦后端来代理请求和添加 'Access-Control-Allow-Origin' header? (可能这样的代理已经存在于某个地方?)或者我可以使用 Progressive Web Apps 功能的东西,比如 Service Workers 吗?或者我应该使用 Electron 或 Cordova 之类的东西吗?我想做的是让我的应用程序也能在移动设备上运行。

这是我的意见,可能是您的要求或其他要求。 设置代理可能真的很痛苦,jsonp 对我来说似乎很麻烦。

您可以编写自己的函数(用于 cors)。 从使用 XMLHttpRequest2(firefox 等)和用于 IE 的 XDomainRequest 开始。

像这样:-

function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {

    // Check if the XMLHttpRequest object has a "withCredentials" property.
    // "withCredentials" only exists on XMLHTTPRequest2 objects.
    xhr.open(method, url, true);

  } else if (typeof XDomainRequest != "undefined") {

    // Otherwise, check if XDomainRequest.
    // XDomainRequest only exists in IE, and is IE's way of making CORS requests.
    xhr = new XDomainRequest();
    xhr.open(method, url);

  } else {

    // Otherwise, CORS is not supported by the browser.
    xhr = null;

  }
  return xhr;
}

var xhr = createCORSRequest('GET', url);
if (!xhr) {
  throw new Error('CORS not supported');
}

参考:- https://www.html5rocks.com/en/tutorials/cors/

显示你如何做 headers 等(滚动到 "Handling a not-so-simple request") 可能对您或其他方面有帮助。 希望这可以帮助 。

How to do Cross-Origin Resource sharing from client?

你不能。如果您的代码可以授予自己访问它喜欢的任何内容的权限,那么拥有权限安全性就毫无意义了。

some thin backend that proxies that requests and adds 'Access-Control-Allow-Origin' header?

如果代理本身是 cross-origin,则只需要添加 header,但是是的:这是在您没有公开数据时绕过 SOP 的标准方法楼主配合。

Probably such proxy already exists somewhere

有很多。我不会推荐任何特定的。

Or could I use something from Progressive Web Apps abilities, like Service Workers?

没有

Or should I use something like Electron or Cordova?

如果您这样做,那么您将编写用户必须明确安装的软件。它不会是一个网络应用程序。 SOP 不适用(至少不以通常的方式)。

您现在可以这样做:

fetch('https://cors-anywhere.herokuapp.com/https://bunyk.wordpress.com/feed/')

...它会正常工作。

这导致向 https://cors-anywhere.herokuapp.com 发出请求,open/public 代理然后将其发送到 https://bunyk.wordpress.com/feed/。当该代理收到响应时,它会接受它并向其添加 Access-Control-Allow-Origin 响应 header,然后将其作为响应传递回您的请求前端代码。

带有 Access-Control-Allow-Origin 响应 header 的响应是浏览器看到的内容,因此浏览器引擎向您显示的错误消息现在消失了,浏览器允许您的前端 JavaScript 访问响应的代码。

或者使用 https://github.com/Rob--W/cors-anywhere/ 中的代码或类似的代码来设置您自己的代理。