同源策略(Same-Origin Policy),是浏览器的一种安全策略
-
同源(即url相同):协议、域名、端口号 必须完全相同。(请求是来自同一个服务)
-
跨域:违背了同源策略,即跨域。
-
ajax请求是遵循同源策略的。
-
同源请求例子(在浏览器访问127.0.0.1:9000/server-orign,然后点击按钮发送同源请求):
-
服务端对同源请求处理:
//3、创建路由规则(request 是请求的报文,response是响应的报文)
app.get('/server-orign', (request, response) => {
//响应一个页面
response.sendFile(__dirname + '/同源策略.html');
});
app.get('/data', (request, response) => {
//响应数据
response.send('服务端返回的数据');
});
- 客户端html:
const btn = document.getElementsByTagName('button')[0];
btn.onclick = function () {
//console.log('测试');
//发送ajax请求
const xhr = new XMLHttpRequest();
xhr.open('GET', '/data');//同源请求,路径可以简写
xhr.send();
xhr.onreadystatechange = function () {
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
console.log(xhr.response);
}
}
}
}
- 同源策略的目的
- 同源策略的限制范围
- 随着互联网的发展,“同源策略”越来越严格,目前,如果非同源,以下三种行为都将收到限制。
// 1. Cookie、LocalStorage 无法读取。不能共享cookie。
// 2. DOM 无法获得,不能互相操作dom
// 3. AJAX 请求不能发送。
解决跨域(JSONP、CORS)
- JSONP
- CORS
- WebSocket