zoukankan      html  css  js  c++  java
  • 跨域请求资源的方式

    文档地址: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);
                                    });
                                });
                }

    结果:

    2、手动解除浏览器跨域的限制

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

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

    右键,创建快捷方式

    右键,点击属性

     

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

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

  • 相关阅读:
    第二个冲刺 6.3.4.学术诚信与职业道德
    第二个冲刺 Sprint
    css之清除浮动
    style和getComputedStyle(ff)和currentStyle
    php 中间件
    Vue 和 angular
    img 分区响应图
    PHP composer
    php实现文件上传,下载的常见文件配置
    php 命名空间
  • 原文地址:https://www.cnblogs.com/oukele/p/10019617.html
Copyright © 2011-2022 走看看