跨域
跨域问题的出现
由于浏览器出于安全考虑的同源策略限制需要跨域,所谓的同源就是两个域需要相同的 协议(protocol)、域名(host)、端口(port)必须相同
三者之前任何一个不同都构成跨域的情况,比如说前后端分离之后,前后都在两个域之下,前端的浏览器请求后端服务器的数据的时候就需要做跨域处理
非同源的限制
1、无法读取非同源网页的 Cooike、LocalStorage、IndexedDB
2、无法接触非同源网页的DOM
3、无法向非同源地址发送AJAX请求
前端跨域常见解决方法
JSONP
JSONP是服务器与客户端跨域通信常用的方法,最大的特点就是简单适用、兼容性好(可以兼容低版本的IE),但是只支持GET请求,不支持POST
思想:由于AJAX会受跨域的影响,但是script不受影响,通过在script中添加JSON数据,服务器收到请求后将数据放在一个回调函数的参数位置传回来
原生解决跨域
<script src="http://test.com/data.php?callback=dosomething"></script>
<script type="text/javascript">
function dosomething(res){
// 处理获得的数据
console.log(res.data)
}
</script>
Vue解决跨域
this.$http.jsonp('http://www.domain2.com:8080/login', {
params: {},
jsonp: 'handleCallback'
}).then((res) => {
console.log(res);
})
CORS(跨域资源分享)
1、普通跨域请求:只需服务器端设置Access-Control-Allow-Origin
2、带cookie跨域请求:前后端都需要进行设置
原生Ajax
var xhr = new XMLHttpRequest(); // IE8/9需用window.XDomainRequest兼容
// 前端设置是否带cookie
xhr.withCredentials = true;
xhr.open('post', 'http://www.domain2.com:8080/login', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send('user=admin');
// 请求状态
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
};
JQuery Ajax
$.ajax({
url: 'http://www.test.com:8080/login',
type: 'get',
data: {},
xhrFields: {
withCredentials: true // 前端设置是否带cookie
},
crossDomain: true, // 会让请求头中包含跨域的额外信息,但不会含cookie
});
axios
axios.defaults.withCredentials = true
服务器端跨域问题的解决
const http = require('http');
const server = http.createServer();
const qs = require('querystring');
server.on('request', function(req, res) {
var postData = '';
// 数据块接收中
req.addListener('data', function(chunk) {
postData += chunk;
});
// 数据接收完毕
req.addListener('end', function() {
postData = qs.parse(postData);
// 跨域后台设置
res.writeHead(200, {
'Access-Control-Allow-Credentials': 'true', // 后端允许发送Cookie
'Access-Control-Allow-Origin': 'http://www.domain1.com', // 允许访问的域(协议+域名+端口)
/*
* 此处设置的cookie还是domain2的而非domain1,因为后端也不能跨域写cookie(nginx反向代理可以实现),
* 但只要domain2中写入一次cookie认证,后面的跨域接口都能从domain2中获取cookie,从而实现所有的接口都能跨域访问
*/
'Set-Cookie': 'l=a123456;Path=/;Domain=www.domain2.com;HttpOnly' // HttpOnly的作用是让js无法读取cookie
});
res.write(JSON.stringify(postData));
res.end();
});
});
server.listen('8080');
console.log('Server is running at port 8080...');