同源策略
为了保护用户隐私,浏览器故意设置的功能限制
- 源 = 协议 + 域名 + 端口号
 - 使用 
window.origin或lacation.origin可以得到当前页面的源 - 两个 url 的协议、域名、端口号完全一致,才是同源, 
[https://baidu.com](https://baidu.com)与[https://www.baidu.com](https://www.baidu.com)不同源 - 不同源的页面之间,不准互相访问数据
 
跨域
访问不同源的资源叫做跨域
CORS
使用 CORS 跨域
跨源资源共享 (CORS) 是一种基于 HTTP 头的机制,该机制通过允许服务器标示除了它自己以外的其它 origin (域,协议和端口),这样浏览器可以访问加载这些资源。
用法:在被请端设置 HTTP 头 “Access-Control-Allow-Origin”:
response.setHeader("Access-Control-Allow-Origin", "http://zhuzhu.com:8989");
JSONP
若不支持 CORS (如IE) 则使用 JSONP 跨域,步骤:
- 被请求端将被请求资源写入一个 JS 文件中,让变量 window.xxx 指向这个资源
 
// friends.jswindow['{{xxx}}']( {{data}} )// server.jsif (path === "/friends.js") {if (request.headers["referer"].indexOf("http://zhuzhu.com:8989") === 0) {response.statusCode = 200;response.setHeader("Content-Type", "text/javascript;charset=utf-8");const string = `window['{{xxx}}']({{data}}) `const data = fs.readFileSync("./public/friends.json").toString();const string2 = string.replace("{{data}}", data).replace('{{xxx}}', query.callback);response.write(string2);response.end();}
- 请求端用 
<script>标签引用这个 JS 文件, 就可以通过 window.XXX({kep: […]}) 获取资源 
<script src="zhuzhu.js"></script>
- 此乃回调的用法,非常巧妙
 
缺点:只能支持 GET 请求,不支持 POST 请求,容易受到 XSS 攻击
