Jquery Ajax实现CORE跨域请求与浏览器禁用同源策略

在我们使用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
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值