我已经阅读了两个小时的反向代理文档以添加 CORS 标头,但我无法使用.你能帮忙举一个简单的例子如何使用它.
I've been reading for two hours the documentation of this Reverse proxy to add CORS headers, and I'm not able to use. Can you please help with a simple example how to use that.
CORS-ANYWHERE
我已经在 javascript 中尝试过该示例
I've tried that example in a 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 或者究竟是什么
I don't understand really if I need node.js or what exactly
CORS Anywhere 帮助访问通常被 Web 浏览器的同源策略禁止的其他网站的数据.这是通过通过服务器(在本例中用 Node.js 编写)代理对这些站点的请求来完成的.
CORS Anywhere helps with accessing data from other websites that is normally forbidden by the same origin policy of web browsers. This is done by proxying requests to these sites via a server (written in Node.js, in this case).
"要使用 API,只需在 URL 前面加上 API URL."一个>.这就是全部.因此,您将请求 https://cors-anywhere.herokuapp.com/http://example.com
,而不是请求 http://example.com
.然后,CORS Anywhere 将代表您的应用程序发出请求,并将 CORS 标头添加到响应中,以便您的 Web 应用程序可以处理响应.
"To use the API, just prefix the URL with the API URL.". That's really all of it. So, instead of requesting http://example.com
, you will request https://cors-anywhere.herokuapp.com/http://example.com
. CORS Anywhere will then make the request on behalf of your application, and add CORS headers to the response so that your web application can process the response.
如果需要,您问题的片段会自动修改 XMLHttpRequest
生成的请求的 URL.此代码段不是必需的,您可以自己添加 CORS Anywhere API URL,就像 在演示页面中.
The snippet from your question automatically modifies the URL for requests generated by XMLHttpRequest
if needed. This snippet is not required, you can just prepend the CORS Anywhere API URL yourself, as done in the demo page.
Github 上的存储库(https://github.com/Rob--W/cors-anywhere) 包含支持 CORS Anywhere 的服务器的源代码.如果您是前端开发人员,那么您只需要知道这些.如果您的应用程序有很多用户,那么您应该自己托管 CORS Anywhere,以避免占用公共 CORS Anywhere 服务器上的所有资源.
The repository on Github (https://github.com/Rob--W/cors-anywhere) contains the source code of the server that powers CORS Anywhere. If you are a front-end dev, then that's all you need to know. If your application has many users, then you should host CORS Anywhere yourself, to avoid eating up all resources on the public CORS Anywhere server.
这篇关于如何在任何地方使用 Cors 反向代理和添加 CORS 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!