在我们使用ajax请求,如果是跨域的话会报以下浏览器错,你应该对下面出现在浏览器控制台里的错误很熟悉。如果你没见过,那只能说明你还年轻
Failed to load https://example.com/: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
Origin ‘https://anfo.pl' is therefore not allowed access.
If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.
其实这并不是错误,而是浏览器的安全策略,如果我们能控制后台请求,只需要在响应头加上允许请求,如果访问的是第三方接口,则无法设置响应头,这个情况,可以通过使用CORS代理来解决,其作为代理请求接口数据,返回正确的跨域响应。
在JS中使用:
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
}
});
//以下ajax请求将会自动在url加上http + '//cors-anywhere.herokuapp.com/'前缀,以实现CORE跨域请求
$.ajax({
url: 'https://www.google.com',
type: 'get',
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log(data)
},
error: function(e) {}
});
注意:
CORS代理会删除Cookie信息。
参考:
http://cors-anywhere.herokuapp.com/
https://stackoverflow.com/questions/15005500/loading-cross-domain-endpoint-with-jquery-ajax
https://github.com/Rob–W/cors-anywhere
另一种方法:这里介绍的是–disable-web-security参数。这个参数可以降低chrome浏览器的安全性,禁用同源策略,利于开发人员本地调试。
使用步骤如下:
1.关闭所有的chrome浏览器。
2.新建一个chrome快捷方式,右键“属性”,“快捷方式”选项卡里选择“目标”,添加 –args --disable-web-security --user-data-dir
3.然后启动chrome