跨域的几种方法

CORS详解

什么是CORS

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

假设为同域的时候

xhr.open('GET','http://127.0.0.1:8080/getNews',true)

没有origin,成功请求到数据
img1

假设输入的域名与Access-Control-Allow-Origin相同

输入的域名也为localhost:8080,也可以获得数据
img2

假设输入的域名与Access-Control-Allow-Origin不相同

那么该浏览器将无法得到数据

源代码
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>

JSONP

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

if(pathObj.query.callback){
	res.end(pathObj.query.callback + '(' + JSON.stringify(news) + ')')
}else{
	res.end(JSON.stringify(news))
}

在html上定义一个函数,那么当服务器器发送这个数据的时候,就相当于先调用这个函数,然后再获取这些数据

降域

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

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

</div>

<script>
document.domain = "jrg.com"
</script>

把两者的域名都降到主域上,如jrg.com

postmessage

<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>

$('.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);
});

给这个事件添加一个message,告诉这个值可以发送数据,然后在监听另一个事件,在收到信息后该怎么办

猜你喜欢

转载自blog.csdn.net/KaisonYi/article/details/89669133