博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
跨域问题
阅读量:4671 次
发布时间:2019-06-09

本文共 1688 字,大约阅读时间需要 5 分钟。

一 引子

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

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

你可能感兴趣的文章
SQA
查看>>
Spring+Struts集成(方案一)
查看>>
在Windows 7中安装、配置和使用IIS7和ASP
查看>>
商业信息敏感、安全处理(口令、数字证书-U盾-密保卡、指纹识别-虹膜识别)...
查看>>
数据库设计的三大范式通俗解释
查看>>
H3C 典型数据链路层标准
查看>>
反向数据库表
查看>>
【原创】Elasticsearch无宕机迁移节点
查看>>
Stripe
查看>>
CC攻击及其解决方法
查看>>
Android安卓手机能不能实现BT文件边下边播?
查看>>
C/C++中printf和C++中cout的输出格式
查看>>
C# CharacterToBinary 将类似2进制字符串 10010110111 转换为数值型源码
查看>>
课后作业-阅读任务-阅读提问-3
查看>>
JavaScript 是一种什么样的语言
查看>>
从零开始写一个Exporter
查看>>
windows10 下使用Pycharm2016 基于Anaconda3 Python3.6 安装Mysql驱动总结
查看>>
.net Thrift 之旅 (二) TServer
查看>>
redis info详解
查看>>
java定时任务调度工具
查看>>