28

我已经阅读了两个小时的反向代理文档以添加 CORS 标头,但我无法使用。你能帮忙举一个简单的例子如何使用它。

CORS-任何地方

我已经在 javascript 中尝试过该示例

(function() {
var cors_api_host = 'cors-anywhere.herokuapp.com';
var cors_api_url = 'https://' + cors_api_host + '/';
var slice = [].slice;
var origin = window.location.protocol + '//' + window.location.host;
var open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
    var args = slice.call(arguments);
    var targetOrigin = /^https?:\/\/([^\/]+)/i.exec(args[1]);
    if (targetOrigin && targetOrigin[0].toLowerCase() !== origin &&
        targetOrigin[1] !== cors_api_host) {
        args[1] = cors_api_url + args[1];
    }
    return open.apply(this, args);
};
})();

我真的不明白我是否需要 node.js 或者究竟是什么

4

3 回答 3

53

CORS Anywhere 有助于访问通常被 Web 浏览器的同源策略禁止的其他网站的数据。这是通过通过服务器(在本例中用 Node.js 编写)代理对这些站点的请求来完成的。

“要使用 API,只需在 URL 前面加上 API URL。” . 这就是全部。因此,http://example.com您将请求而不是请求https://cors-anywhere.herokuapp.com/http://example.com。然后,CORS Anywhere 将代表您的应用程序发出请求,并将 CORS 标头添加到响应中,以便您的 Web 应用程序可以处理响应。

如果需要,您问题中的代码段会自动修改生成的请求的 URL XMLHttpRequest。此代码段不是必需的,您可以自己添加 CORS Anywhere API URL,如演示页面中所做的那样。

Github 上的存储库 ( https://github.com/Rob--W/cors-anywhere ) 包含支持 CORS Anywhere 的服务器的源代码。如果您是前端开发人员,那么您只需要知道这些。如果您的应用程序有很多用户,那么您应该自己托管 CORS Anywhere,以避免占用公共 CORS Anywhere 服务器上的所有资源。

于 2015-08-23T13:15:29.493 回答
33

我听从 Rob 的意见,但这是我试图回答你的问题。

(Rob,请随时更正此答案;感谢您使用 CORS Anywhere。它最近为我节省了很多麻烦。)

  1. 安装Node.js
  2. 随处安装CORS

    例如,在命令提示符下,输入:

    npm install cors-anywhere

    (此示例命令将 CORS Anywhere 安装在当前目录下,位于node_modules\cors-anywhere.)

  3. 随时随地运行 CORS。

    例如,在命令提示符下,输入:

    node cors-anywhere.js

CORS Anywhere 以如下消息响应:

Running CORS Anywhere on 127.0.0.1:8080

(IP 地址127.0.0.1localhost; 您的计算机。)

您可以在环境变量中指定端口,但我选择在本地副本中编辑cors-anywhere.js.

现在,假设您要在以下 URL 使用未启用 CORS 的 Web 服务:

http://remote.server.com:8085/service

您不使用原始 URL,而是使用 CORS Anywhere 域和端口,然后使用原始 URL 作为路径组件:

http://localhost:8080/remote.server.com:8085/service

(您可以省略http://原始 URL 的开头。)

于 2016-12-14T07:51:15.317 回答
0

[我意识到我使用的 corsanywhere 与您的不同。我使用这个没有连字符,corsanywhere 而不是 cors-anywhere。因此,如果您愿意,可以尝试这个,因为它似乎仍然可以正常工作:

https://corsanywhere.herokuapp.com/https://api.yelp.com/v3/businesses/search?term=pizza&location=$dallas&sort_by=rating 编辑:好像这样(没有连字符)可能不是官方版本所以谨慎使用。] 1

于 2021-10-14T14:20:49.540 回答