使用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: 'https://www.google.com',
type: 'get',
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log(data)
},
error: function(e) {}
});
注意:
CORS代理会删除Cookie信息。
参考:
https://stackoverflow.com/questions/15005500/loading-cross-domain-endpoint-with-jquery-ajax
https://github.com/Rob–W/cors-anywhere