个性化阅读
专注于IT技术分析

如何使用XMLHttpRequest(jQuery Ajax)绕过”Access-Control-Allow-Origin”错误

点击下载

如果你是一个好奇的开发人员, 那么你可能已经面临(或将要面临)跨域/同源政策。此政策规定, 你无法从你自己的域以外的其他域检索信息(www.mydomain.com无法执行对www.otherdomain.com的异步调用)。幸运的是, 有一个名为CORS Anywhere的免费代理服务器, 该服务器将CORS标头添加到代理请求中。

为了使用javascript轻松解决此问题, 我们将像往常一样使用XMLHttpRequest或jQuery ajax发出ajax请求, 但我们将使用cors-anywhere服务, 这使我们可以绕过此问题。 CORS Anywhere是一个NodeJS反向代理, 它将CORS标头添加到herokuapp中托管的代理请求中。

代理的URL实际上是从路径中获取, 经过验证和代理的。代理URI的协议部分是可选的, 默认为” http”。如果指定了端口443, 则协议默认为” https”。除cookie之外, 此程序包对http方法或标头没有任何限制。不允许请求用户凭据。

你只需要在请求URL https://cors-anywhere.herokuapp.com上添加前缀即可解决问题。

jQuery的

// In this example, if you make an ajax request to the following website
var myUrl = 'http://www.geoplugin.net/json.gp?ip=216.58.209.68';
//  But if you make it from a browser, then it will work without problem ...

// However to make it work, we are going to use the cors-anywhere free service to bypass this
var proxy = 'https://cors-anywhere.herokuapp.com/';

$.ajax({
    // The proxy url expects as first URL parameter the URL to be bypassed
    // https://cors-anywhere.herokuapp.com/{my-url-to-bypass}
    url: proxy + myUrl, complete:function(data){
        console.log(data);
    }
});

或使用$ .get, $。getJSON或$ .post的快捷方式:

var myUrl = 'http://www.geoplugin.net/json.gp?ip=216.58.209.68';

var proxy = 'https://cors-anywhere.herokuapp.com/';

var finalURL = proxy + myUrl;

// With the get JSON (frequently used) method
$.getJSON(finalURL, function( data ) {
    console.log(data);
});

// With the get method
$.get(finalURL, function( data ) {
    console.log(data);
});

// With the post method
$.post(finalURL, function( data ) {
    console.log(data);
});

XMLHttpRequest

// In this example, if you make an ajax request to the following website
var myUrl = 'http://www.geoplugin.net/json.gp?ip=216.58.209.68';
//  But if you make it from a browser, then it will work without problem ...

// However to make it work, we are going to use the cors-anywhere free service to bypass this
var proxy = 'https://cors-anywhere.herokuapp.com/';

// Execute request
var oReq = new XMLHttpRequest();

oReq.addEventListener("load", function () {
    console.log(this.responseText);
});
// Or post, etc
oReq.open("GET", proxy + myUrl);
oReq.send();

这种方法只有两个局限性:

  • 不代理Cookie
  • 不允许请求用户凭据

玩得开心 !

赞(0)
未经允许不得转载:srcmini » 如何使用XMLHttpRequest(jQuery Ajax)绕过”Access-Control-Allow-Origin”错误

评论 抢沙发

评论前必须登录!