美文网首页
跨域的解决方式

跨域的解决方式

作者: billa_8f6b | 来源:发表于2017-06-15 00:05 被阅读0次

jsonp

html中可以通过script标签引入其他域的js,利用这一特性,结合后端支持,可以实现跨域访问接口
实现原理:

  1. 定义数据处理函数_fun
  2. 创建script标签,src的地址执行后端接口,最后加个参数callback=fun
  3. 服务端在收到请求后,解析参数,计算返还数据,输出 fun(data) 字符串。
  4. fun(data)会放到script标签做为js执行。此时会调用fun函数,将data做为参数。

前端代码:

<div class="query-area">
        <input type="text" name="username" value="hunger" placeholder="hunger, ruoyu, anyone">
        <button>查询朋友</button>   
    </div>
    <div class="detail-area">
        <ul>     
        </ul>
    </div>
    <script>
        var btn = document.querySelector('.query-area button');
        var input = document.querySelector('.query-area input');
        btn.addEventListener('click', function(){
        var script=document.createElement("script");
        script.src="http://a.test.com:8080/getFriends?username="+input.value+"&callback=render";
        document.head.appendChild(script);
        document.head.removeChild(script);
        });
        function render(friends){
        var detailCt = document.querySelector('.detail-area ul');
        detailCt.innerHTML = '';
        var ct = document.createDocumentFragment();
        for(var i = 0; i < friends.length; i++){
            var node = document.createElement('li');
            node.innerText = friends[i];
            ct.appendChild(node)
        }
        detailCt.appendChild(ct)
        }
    </script>

后台代码:

router.get('/getFriends', function(req, res) {
        var username = req.query.username ;// 通过 req.query获取请求参数
        var friends;
    
    //根据请求参数mock数据
    switch (username){
        case 'ruoyu':
            friends = ['小米', '小刚'];
            break;
        case 'hunger':
            friends = ['小谷', '小花'];
            break;
        default:
            friends = ['没有朋友'];
    }
    var cb=req.query.callback;
    res.send(cb+'('+JSON.stringify(friends)+')')
    });

CORS

CORS 全称是跨域资源共享(Cross-Origin Resource Sharing),是一种 ajax 跨域请求资源的方式,支持现代浏览器,IE支持10以上。
实现方式:

  1. 使用XMLHttpRequest发送请求时,服务器发现不同源会在请求中加一个请求头Origin
  2. 后台确定接受该请求,则在响应头中加一个Access-Control-Allow-Origin
  3. 浏览器判断该响应头中包含origin则响应请求,没有不响应

前端代码:

    <div class="query-area">
        <input type="text" name="username" value="hunger" placeholder="hunger, ruoyu, anyone">
        <button>查询朋友</button>   
    </div>
    <div class="detail-area">
        <ul>     
        </ul>
    </div>

    <script>
        var btn = document.querySelector('.query-area button');
        var input = document.querySelector('.query-area input');
    
        btn.addEventListener('click', function(){
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 304)){
            var friends = JSON.parse(xhr.responseText);
            render(friends)
            }
        };
            xhr.open('get', 'http://a.test.com:8080/getFriends?username=' + input.value, true);
            xhr.send();
        });
        function render(friends){
        var detailCt = document.querySelector('.detail-area ul');
        detailCt.innerHTML = '';
        var ct = document.createDocumentFragment();
        for(var i = 0; i < friends.length; i++){
            var node = document.createElement('li');
            node.innerText = friends[i];
            ct.appendChild(node)
        }
        detailCt.appendChild(ct)
        }
    </script>

后台代码:

    router.get('/getFriends', function(req, res) {
        var username = req.query.username ;// 通过 req.query获取请求参数
        var friends;
    //根据请求参数mock数据
    switch (username){
        case 'ruoyu':
            friends = ['小米', '小刚'];
            break;
        case 'hunger':
            friends = ['小谷', '小花'];
            break;
        default:
            friends = ['没有朋友'];
    }
        res.header("Access-Control-Allow-Origin", "http://b.test.com:8080");
        res.send(friends);
    });

降域

降域的使用条件是两个名的一级域名相同(例如: a.test.com 与 b.test.com)都同属于test.com这个域名

测试时需使用a.test.com:8080/a.html访问,不能使用localhost,否则会报错:报错信息为不能把domain设置为test.com

a.html

    <html>
    <style>
        .ct {
            width: 910px;
            margin: auto;
        }
        
        .main {
            float: left;
            width: 450px;
            height: 300px;
            border: 1px solid #ccc;
        }
        
        .main input {
            margin: 20px;
            width: 200px;
        }
        
        .iframe {
            float: right;
        }
        
        iframe {
            width: 450px;
            height: 300px;
            border: 1px dashed #ccc;
        }
    </style>

    <div class="ct">
        <h1>使用降域实现跨域</h1>
        <div class="main">
            <input type="text" placeholder="http://a.test.com:8080/a_jiangyu.html">
        </div>

        <iframe src="http://b.test.com:8080/b_jiangyu.html" frameborder="0"></iframe>

    </div>


    <script>
        //URL: http://a.jrg.com:8080/a.html
        document.querySelector('.main input').addEventListener('input', function() {
            console.log(this.value);
            window.frames[0].document.querySelector('input').value = this.value;
        })

        //取一级域名作为domain
        document.domain = "test.com"
    </script>

    </html>

b.html

    <html>
    <style>
        html,
        body {
            margin: 0;
        }
        
        input {
            margin: 20px;
            width: 200px;
        }
    </style>

    <input id="input" type="text" placeholder="http://b.jiangyu.com:8080/b.html">
    <script>
        // URL: http://b.jrg.com:8080/b.html

        document.querySelector('#input').addEventListener('input', function() {
            window.parent.document.querySelector('input').value = this.value;
        })

        //取一级域名作为domain
        document.domain = 'test.com';
    </script>

    </html>

PostMessage

使用window.postMessage() 实现
postMessage的原理是会向另一个地方发送信息,另一个地方通常是iframe,或者是由当前页面弹出的窗口。参数是:信息以及表示接受消息方的来自哪个域的字符串,如果给定*便是不限定接受者的域。

a.html

    <html>
    <style>
        .ct {
            width: 910px;
            margin: auto;
        }
        
        .ct h1 {
            text-align: center;
        }
        
        .main {
            float: left;
            width: 450px;
            height: 300px;
            border: 1px solid #ccc;
        }
        
        .main input {
            margin: 20px;
            width: 200px;
        }
        
        .iframe {
            float: right;
        }
        
        iframe {
            width: 450px;
            height: 300px;
            border: 1px dashed #ccc;
        }
    </style>

    <div class="ct">
        <h1>使用postMessage实现跨域</h1>
        <div class="main">
            <input type="text" placeholder="http://a.test.com:8080/a.html">
        </div>

        <iframe src="http://localhost:8080/b.html" frameborder="0"></iframe>

    </div>


    <script>
        //URL: http://a.test.com:8080/a.html
        $('.main input').addEventListener('input', function() {
            window.frames[0].postMessage(this.value, '*');
        })
        window.addEventListener('message', function(e) {
            $('.main input').value = e.data
        });

        function $(id) {
            return document.querySelector(id);
        }
    </script>

    </html>

b.html

    <html>
    <style>
        html,
        body {
            margin: 0;
        }
        
        input {
            margin: 20px;
            width: 200px;
        }
    </style>

    <input id="input" type="text" placeholder="http://b.test.com:8080/b.html">
    <script>
        // URL: http://b.test.com:8080/b.html

        $('#input').addEventListener('input', function() {
            window.parent.postMessage(this.value, '*');
        })
        window.addEventListener('message', function(e) {
            $('#input').value = e.data
        });

        function $(id) {
            return document.querySelector(id);
        }
    </script>

    </html>

相关文章

  • springboot 在整合shiro后,跨域就失效了。

    原springboot 解决跨域问题 使用 tomcat 中的 Filter的方式解决跨域

  • 跨域

    ??JSONP只能解决GET请求跨域,不能解决POST请求跨域问题,XHR2可以解决GET,POST方式的请求跨域...

  • AJAX

    题目 手写一个ajax 跨域的常用实现方式 知识点 XMLHttpRequest 状态码 跨域:同源策略,跨域解决...

  • Vue实现跨域请求

    一般解决跨域问题可以通过CORS跨域、JSONP和反向代理跨域。下面分别介绍这三种跨域方式: 1、CORS 以ne...

  • SpringBoot 实现前后端分离的跨域访问(CORS)

    springBoot小白写博客时遇到了跨域问题,顺便记录一下踩过的坑 springboot解决跨域的几种方式 方式...

  • Flask-cors跨域

    什么是跨域 为什么要考虑跨域问题 同源策略 解决跨域问题 方式一: 使用 JSONP (一种非Ajax技术,需要前...

  • 跨域解决方式

    出于安全方面的考虑,浏览器遵从同源策略的原则。即同协议(http/https)、同域名(jianshu.com/j...

  • 跨域解决方式

    JSONP实现跨域 原理:网页通过添加一个 元素,向服务器请求JSON数据,这种做法不受同源政策限制;服务器收到请...

  • 跨域 & 跨域的几种解决方式

    什么是跨域 跨域是由于浏览器同源策略的限制,它是对 JavaScript 的限制。浏览器不允许执行其他网站的脚本 ...

  • 浏览器跨域及其解决方案

    title: 浏览器跨域及其解决方案author: Maydate: 20220428 什么是跨域跨域的表现解决跨...

网友评论

      本文标题:跨域的解决方式

      本文链接:https://www.haomeiwen.com/subject/rbaeqxtx.html