4-1初始跨域|4-3跨域资源共享|4-4JSONP
跨域是什么
<script>
//1.跨域是什么
//同域,不是跨域
//const url = './index.html';
// const url = 'https://www.baidu.com';//不同域
// const xhr = new XMLHttpRequest();
/* Access to XMLHttpRequest at 'https://www.baidu.com/' from origin 'http://127.0.0.
1:8848' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is
present on the requested resource.
*/
//想一个域发送请求,如果请求的域和当前与是不同域,就要跨域
//不同域之间的请求,就是跨域请求
// xhr.onreadystatechange = () => {
// if (xhr.readyState != 4) return;
// if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
// console.log(xhr.responseText);
// }
// };
// xhr.open('GET', url, true);
// xhr.send(null);
</script>
什么是不同域,什么是同域
https(协议)://www.imooc.com(域名):443(端口号)/course/list(路径)
协议、域名、端口号、任何一不一样无所谓
不同域
https://www.imooc.com:443/course/list
https://www.imooc.com:80/course/list
http://www.imooc.com:80/course/list
http://m.imcco.com:80/course/list
http:/imcco.com:80/course/list
同域
htpp://imooc.com:80
htpp://imooc.com:80/course/list
跨域请求为什么会被阻止
阻止跨域请求,其实浏览器本身得一种安全策略-同源策略
其他客户端或服务端都不存在跨域被阻止的问题
跨域解决方案
CORS跨域资源共享
JSONP
有限使用CORS跨域资源共享,如果浏览器不支持CORS的话,在使用JSONP
CORS跨域资源共享
什么是CORS
//const url = 'https://www.imooc.com';//不同域 const url ='https://www.imooc.com/api/http/search/suggest?words=js'; const xhr = new XMLHttpRequest(); xhr.onreadystatechange = () => { if (xhr.readyState != 4) return; if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) { console.log(xhr.responseText); } }; xhr.open('GET', url, true); xhr.send(null); //Access-Control-Allow-Origin: * //表名允许所有域名来跨域请求它,*是通配符,没有任何限制 //只允许指定域名的跨域请求 Access-Control-Allow-Origin:http://127.0.0.1:5500
使用CORS跨域的过程
浏览器发送请求
后端在响应头中添加Access-Control-Allow-Origin 头信息
浏览器接收到响应
如果是同城下的请求,浏览器不会额外做什么,这次前后端通信就圆满完成了
如果是跨域请求,浏览器会从响应头中查找是否允许跨越访问
如果允许跨域,通信圆满完成
如果没有找到或者不好含想要跨域的域名,就丢弃响应结果
CORS的兼容性
IE10及以上版本的浏览器可以正常使用CORS
JSONP原理
JSONP的原理
script标签跨域不会被浏览器阻止
JSONP主要就是利用script标签,加载跨域文件
使用JSONP实现跨域
服务器端准备好JSONP接口
https://www.imooc.com/api/http/jsonp?callback=handleResPonse
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JSONP</title>
</head>
<body>
<script>
//1.JSONP的原理
//script标签跨域不会被浏览器阻止
//JSONP主要就是利用script标签,加载跨域文件
//2.使用JSONP实现跨域
//服务器端准备好JSONP实现跨域
//手动加载JSONP接口 或者动态加载JSONP接口
const script = document.createElement('script');
script.src ='https://www.imooc.com/api/http/jsonp?callback=ab';
document.body.appendChild(script)
//声明函数
const ab = data =>{
console.log(data)
};
/* ab({
"code": 200, "data": [ { "word": "jsp" },
{ "word": "js" }, { "word": "json" },
{ "word": "js 入门" }, { "word": "jstl" } ] });
*/
</script>
<!-- <script src="https://www.imooc.com/api/http/jsonp?callback=ab"></script> -->
<!-- 相当于 -->
<!-- <script>
{ "code": 200, "data": [ { "word": "jsp" }, { "word": "js" }, { "word": "json" }, { "word": "js 入门" }, { "word": "jstl" } ] }
</script> -->
</body>
</html>

浙公网安备 33010602011771号