什么是跨域,如何解决跨域
1、网络协议不同 http,https
2、域名不同
3、子域名不同
4、端口不同 8080
跨域解决方法:
1、使用CORS
后端人员在处理请求的时候,添加允许跨域请求
res.writeHead(200, {
"Content-Type": "text/html; charset=UTF-8",
"Access-Control-Allow-Origin":'http://localhost',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'X-Requested-With, Content-Type'
});
2、使用JSONP和script标签(此无法post请求)
使用script标签,引入目标域和目标域资源,获取的数据一般为json格式。
<script>
function testjsonp(data) {
console.log(data.name); // 获取返回的结果
}
</script>
<script>
var _script = document.createElement('script');
_script.type = "text/javascript";
_script.src = "http://localhost:8888/jsonp?callback=testjsonp";
document.head.appendChild(_script);
</script>