同源策略是何物?

所谓同源策略,指的是浏览器对不同源的脚本或者文本的访问方式进行的限制。比如源a的js不能读取或设置引入的源b的元素属性。那么先定义下什么是同源,所谓同源,就是指两个页面具有相同的协议,主机(也常说域名),端口,三个要素缺一不可。

看下面的比较就一目了然了:

 
URL1 URL2 说明 是否允许通信
https://github.com/LoveCatDog/StudyOne https://github.com/LoveCatDog/cms-admin-mall 协议、域名、端口都相同 允许
https://github.com/LoveCatDog/cms-admin-mall https://github.com:8080/LoveCatDog/cms-admin-mall 协议、域名相同、端口不同 不允许
http://github.com/LoveCatDog/cms-admin-mall https://github.com/LoveCatDog/cms-admin-mall 域名相同、端口相同、协议不同  不允许
https://github.com/LoveCatDog/cms-admin-mall https://cnblogs.com/LoveCatDog/cms-admin-mall
协议、端口相同、域名不同  不允许
 https://github.com/LoveCatDog/cms-admin-mall  https://www.github.com/LoveCatDog/cms-admin-mall 协议、端口相同、主域名相同、子域名不同  不允许

同源策略限制的不同源之间的交互主要针对的是js中的XMLHttpRequest等请求,写代码的时候也常常会引用其他域名的js文件,样式文件,图片文件什么的,这些则不会收到限制

未来的我会感谢现在努力的自己。
原文地址:https://www.cnblogs.com/cat-eol/p/11776321.html