跨域问题

一 引子

  如果你对下面几句代码有清晰的思路,那么本篇文章可以略过.

1 header("Access-Control-Allow-Origin:*");
2 header("Access-Control-Allow-Headers DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type");
3 header("Access-Control-Allow-Methods GET,POST,OPTIONS"); 

此处三行代码用于从后端解决跨域问题.那么跨域问题到底是怎么回事呢?

1 In computing, the same-origin policy is an important concept in the web application security model. Under the policy, a web browser permits scripts
2  contained in a first web page to access data in a second web page, but only if both web pages have the same origin. An origin is defined as a 
3 combination of URI scheme, hostname, and port number. This policy prevents a malicious script on one page from obtaining access to 
4 sensitive data on another web page through that page's Document Object Model.

人话--->同域是指相同的URI scheme, 主机名和端口号.uri scheme这里理解为uri protocol ,like http,ftp,file,svn,etc. APIs是restful 富媒体web应用构建不可缺少的一部分,一些api的返回是敏感的,你不想开放给其他host,http默认集成了这种security mechanism.在不想重复造轮子的时候,就需要使用跨域了.

二 机制

  浏览器检测到跨域的,使用options 方法在header中加上参数origin,后端检测来源origin不在Access- Control-Allow-Origin,可以做策略,或者直接返回给浏览器,浏览器检测返回的options字段中Access-Control- Allow-Origin,是否包含本域,不包含则浏览器报错,7层应用层拒绝这个包,但实际上这个packet是收到了的.

三 解决方案

  1. 在服务器端返回时加入header,如本文开头三行代码.第一行代码解决域名问题,下面两行代码确保部分需要的header可以被C端正确解读.

    2. 使用jsonp解决.利用<script >的src属性,或者用ajax

1      jsonpCallback: "showPrice",  //自定义处理函数
2      jsonp: "callback",        //与后端交互的接口
3    dataType: "jsonp",        //datatype标明是jsonp

   服务器端php代码写$_GET['callback'] || $_POST['callback']; 回传参数$callback=(json_encode($res));

 

还有使用代理,iframe ,本地存储等解决方案,个人感觉不如jsonp和h5的headers 好用,所以不再赘述.

原文地址:https://www.cnblogs.com/liuyuxing/p/5073243.html