跨域的几种方法

JSONP(JSON with padding)

JSONP是通过 script 标签加载数据的方式去获取数据当做 JS 代码来执行 提前在页面上声明一个函数,函数名通过接口传参的方式传给后台,后台解析到函数名后在原始数据上「包裹」这个函数名,发送给前端。换句话说,JSONP 需要对应接口的后端的配合才能实现。

创建服务器server.js:
var http = require('http')
var fs = require('fs')
var path = require('path')
var url = require('url')

http.createServer(function(req, res){
  var pathObj = url.parse(req.url, true)

  switch (pathObj.pathname) {
    case '/getNews':
      var news = [
        "第11日前瞻:中国冲击4金 博尔特再战200米羽球",
        "正直播柴飚/洪炜出战 男双力争会师决赛",
        "女排将死磕巴西!郎平安排男陪练模仿对方核心"
        ]
      
      
     //防止乱码
      res.setHeader('Content-Type','text/json; charset=utf-8')
      
    //后端支持jsonp
      if(pathObj.query.callback){
        res.end(pathObj.query.callback + '(' + JSON.stringify(news) + ')')
      }else{
        res.end(JSON.stringify(news))
      }

      break;

    default:
      fs.readFile(path.join(__dirname, pathObj.pathname), function(e, data){
        if(e){
          res.writeHead(404, 'not found')
          res.end('<h1>404 Not Found</h1>')
        }else{
          res.end(data)
        }
      }) 
  }
}).listen(8080)

页面index.html:

<!DOCTYPE html><html><body>
  <div class="container">
    <ul class="news">
    </ul>
    <button class="show">show news</button>
  </div>

<script>

  $('.show').addEventListener('click', function(){
    var script = document.createElement('script');
    script.src = 'http://127.0.0.1:8080/getNews?callback=appendHtml';
    document.head.appendChild(script);
    document.head.removeChild(script);
  })

  function appendHtml(news){
    var html = '';
    for( var i=0; i<news.length; i++){
      html += '<li>' + news[i] + '</li>';
    }
    console.log(html);
    $('.news').innerHTML = html;
  }

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

</html>

CORS(Cross-Origin Resource Sharing)

CORS 全称是跨域资源共享(Cross-Origin Resource Sharing),是一种 ajax 跨域请求资源的方式,支持现代浏览器,IE支持10以上。 实现方式很简单,当你使用 XMLHttpRequest 发送请求时,浏览器发现该请求不符合同源策略,会给该请求加一个请求头:Origin,后台进行一系列处理,如果确定接受请求则在返回结果中加入一个响应头:Access-Control-Allow-Origin; 浏览器判断该相应头中是否包含 Origin 的值,如果有则浏览器会处理响应,我们就可以拿到响应数据,如果不包含浏览器直接驳回,这时我们无法拿到响应数据。所以 CORS 的表象是让你觉得它与同源的 ajax 请求没啥区别,代码完全一样。

服务器server.js

var http = require('http')
var fs = require('fs')
var path = require('path')
var url = require('url')

http.createServer(function(req, res){
  var pathObj = url.parse(req.url, true)

  switch (pathObj.pathname) {
    case '/getNews':
      var news = [
        "第11日前瞻:中国冲击4金 博尔特再战200米羽球",
        "正直播柴飚/洪炜出战 男双力争会师决赛",
        "女排将死磕巴西!郎平安排男陪练模仿对方核心"
        ]

    //访问控制允许的域
      res.setHeader('Access-Control-Allow-Origin','http://localhost:8080')
      
    //允许所有
    //res.setHeader('Access-Control-Allow-Origin','*')
      
      res.end(JSON.stringify(news))
      break;
    default:
      fs.readFile(path.join(__dirname, pathObj.pathname), function(e, data){
        if(e){
          res.writeHead(404, 'not found')
          res.end('<h1>404 Not Found</h1>')
        }else{
          res.end(data)
        }
      }) 
  }
}).listen(8080)
页面index.html
<!DOCTYPE html><html><body>
  <div class="container">
    <ul class="news">

    </ul>
    <button class="show">show news</button>
  </div>

<script>

  $('.show').addEventListener('click', function(){
    var xhr = new XMLHttpRequest()
    xhr.open('GET', 'http://127.0.0.1:8080/getNews', true)
    xhr.send()
    xhr.onload = function(){
      appendHtml(JSON.parse(xhr.responseText))
    }
  })

  function appendHtml(news){
    var html = ''
    for( var i=0; i<news.length; i++){
      html += '<li>' + news[i] + '</li>'
    }
    $('.news').innerHTML = html
  }

  function $(selector){
    return document.querySelector(selector)
  }
</script>
</html>

document.domain-降域

对于主域相同而子域不同的情况下,可以通过设置 document.domain 的办法来解决,具体做法是可以在 http://www.example.com/a.htmlhttp://sub.example.com/b.html两个文件分别加上 document.domain = "a.com";然后通过 a.html 文件创建一个 iframe,去控制 iframe 的 window,从而进行交互,当然这种方法只能解决主域相同而二级域名不同的情况,

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

<script>
  document.querySelector('#input').addEventListener('input',function() {
    window.parent.document.querySelector('input').value = this.value
  })
  document.domain = 'jrg.com'
</script>

使用postMessage实现跨域

发送方使用postMessage方法向接收方推送消息,第一个参数为推送的内容,第二个参数是允许被访问的域名;接收方通过监听message的方法接收数据

a.html
<body>
  <div class="ct">
    <h1>使用postMessage实现跨域</h1>
    <div class="main">
      <input type="text" placeholder="http://a.jrg.com:8080/a.html">
    </div>
    <iframe src="http://localhost: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.jrg.com:8080/b.html">
  <script>
    $('#input').addEventListener('input', function () {
      console.log(this.value)
      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>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 什么是跨域 浏览器出于安全方面的考虑,只允许客户端与本域(同协议、同域名、同端口,三者缺一不可)下的接口交互。不同...
    七里之境阅读 1,489评论 0 0
  • 1. AJAX AJAX(Asynchronous JavaScript and XML),意思就是用JavaSc...
    公子七阅读 5,305评论 0 5
  • 同源策略 浏览器出于安全方面的考虑,为了保证用户信息的安全,防止恶意的网站窃取数据。只允许与本域下的接口交互。不同...
    祝余_scrapy阅读 513评论 0 0
  • 跨域 同源策略 浏览器出于安全方面的考虑,只允许与本域下的接口交互。不同源的客户端脚本在没有明确授权的情况下,不能...
    8184ed277c6e阅读 749评论 0 4
  • 概念:只要协议、域名、端口有任何一个不同,都被当作是不同的域。 所有具有 src 属性的HTML标签都可以跨域 原...
    jeffAAA阅读 2,703评论 0 0

友情链接更多精彩内容