Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
677 views
in Technique[技术] by (71.8m points)

javascript - How to use Cors anywhere to reverse proxy and add CORS headers

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

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);
};
})();

I don't understand really if I need node.js or what exactly

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

"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.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...