跨域

2017-11-22  本文已影响0人  别让我一个人醉_1fa7

同源策略

实现跨域的方法

1 jsonp

var express = require('express');
var app = express();

app.get('/a',function(req,res){
    var callback = req.query.callback;
    if(callback){
        res.send(callback+'("data")')
    }else{
        res.send("abc")
    }
})
app.listen(3000)
console.log('success')

2 cores

var express = require('express');
var app = express();

app.get('/a',function(req,res){
    var callback = req.query.callback;
    if(callback){
        res.send(callback+'(data)')
    }else{
        res.header("Access-Control-Allow-Origin","*")
        res.send("abc")
    }
})
app.listen(3000)
console.log('success')

3 降域

a.html
<div class="ct">
 <h1>使用降域实现跨域</h1>
 <div class="main">
   <input type="text" placeholder="http://a.ji.com:8080/a.html">
 </div>
 <iframe src="http://b.ji.com:8080/b.html" frameborder="0" ></iframe>
</div>
<script>
document.querySelector('.main input').addEventListener('input', function(){
 window.frames[0].document.querySelector('input').value = this.value;
})
document.domain = "ji.com"
</script>
b.html
<body>
    <input id="input" type="text"  placeholder="http://b.ji.com:8080/b.html">
    <script>
    document.querySelector('#input').addEventListener('input', function(){
        window.parent.document.querySelector('input').value = this.value;
    })
    document.domain = 'ji.com';
    </script>
</body>

4 postMessage

a.html
<body>
  <div class="ct">
    <h1>使用postMessage实现跨域</h1>
    <div class="main">
      <input type="text" placeholder="http://a.ji.com:8080/a.html">
    </div>
    <iframe src="http://b.ji.com:8080/b.html" frameborder="0" ></iframe>
  </div>
  <script>
  $('.main input').addEventListener('input', function(){
    console.log(this.value);
    window.frames[0].postMessage(this.value,'*');
  })
  window.addEventListener('message',function(e) {
      $('.main input').value = e.data
      console.log(e.data);
  });
  function $(id){
    return document.querySelector(id);
  }
  </script>
</body>
b.html
<body>
    <input id="input" type="text"  placeholder="http://b.ji.com:8080/b.html">
    <script>
    $('#input').addEventListener('input', function(){
        window.parent.postMessage(this.value, '*');
    })
    window.addEventListener('message',function(e) {
            $('#input').value = e.data
        console.log(e.data);
    });
    function $(id){
        return document.querySelector(id);
    }
    </script>
</body>
上一篇 下一篇

猜你喜欢

热点阅读