跨域请求资源的方式

文档地址:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS?tdsourcetag=s_pcqq_aiomsg#HTTP_%E5%93%8D%E5%BA%94%E9%A6%96%E9%83%A8%E5%AD%97%E6%AE%B5

1、使用jsonp跨域

   原生实现

        <script >
            //点击事件
            document.getElementById("btn").onclick = function(){
            
                //生成一个script元素
                var script = document.createElement("script");
                //给srcipt的src赋值  传参并指定回调执行函数为take
                script.src = "http://localhost:8080/kuayu0?callback=take";
                //将生成的script追加到head中
                document.head.appendChild(script);
            
            }
       //回调执行函数
function take(resp){ console.log(resp); } </script>

 服务端的设置

运行结果:

 使用 jquery ajax

            //点击事件
            document.getElementById("btn").onclick = function() {

                $.ajax({
                    url: 'http://localhost:8080/kuayu0',
                    type: 'get',
                    dataType: 'jsonp', // 请求方式为jsonp
                    jsonpCallback: "take", // 自定义回调函数名
                    data: {}
                });
            }

            function take(resp) {
                console.log(resp);
            }
        </script>

2、跨域资源共享(CORS)

在服务端设置头部信息。

 

请求

            //点击事件
            document.getElementById("btn").onclick = function() {

                            fetch("http://localhost:8080/kuayu1",{
                                method:"get"
                            }).then(function(resp){
                                resp.text().then(function(data){
                                    console.log(data);
                                });
                            });
            }

结果:

要是你问,我要是调用别人的接口得到的数据呢?

我还有一个最强硬的方法(将浏览器的同源策略给关闭了)这里以谷歌浏览器为示例。

右键,创建快捷方式

右键,点击属性

 

后面加上  --disable-web-security  --user-data-dir=e:\xxx 然后点击确定

然后打开这个浏览器,你就会发现可以跨域了。(用完要记得关闭啊,这是很不安全的,访问期间它会偷偷的下载东西放在e盘的xxx文件夹中,存在路径也是可以设置的哦)

猜你喜欢

转载自www.cnblogs.com/oukele/p/10019617.html