同源策略和跨域

同源策略和跨域

1. 同源策略

1.1 什么是同源

image-20230521165459428

1.2 什么是同源策略

image-20230521165506350

2. 跨域

2.1 什么是跨域

image-20230521165519464

2.2 浏览器对跨域请求的拦截

image-20230521165524996

2.3 如何实现跨域数据请求

image-20230521165531916

2.4 跨域示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="/lib/jquery-3.6.0.js"></script>
</head>

<body>
<script>
// Access to XMLHttpRequest at 'http://jsfiddle.net/echo/jsonp/' from origin 'http://127.0.0.1:3000'
// has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
$.ajax({
url: 'http://jsfiddle.net/echo/jsonp/',
type: 'GET',
dataType: 'json',
data: { id: 123 },
success: function (data) {
console.log(data);
}
})
</script>
</body>

</html>

image-20230521165611192