同源策略

同源:协议相同、域名相同、端口号相同

如果非同源那么将收到的限制:

  • Cookie、LocalStorage和IndexDB无法读取
  • DOM无法获得
  • AJAX请求不能发送

互联网默认原则:同源策略(不允许跨域访问)

常见跨域

  • link元素
  • script元素
  • img元素
  • iframe元素

JSONP

通过动态创建 script 标签,通过 script 标签的 src 请求没有域限制来获取资源

例如在 html 页面中,将 script 标签地址改为后端接口。

网页通过添加一个<script>元素,向服务器请求JSON数据,这种做法不受同原政策限制;服务器收到请求后,将数据放在一个指定名的回调函数里传回来。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>

<body>
<script>
function fn(data) {
console.log(data);
}
</script>
<script src="http://127.0.0.1:3000?callback=fn"></script>
</body>

</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const http = require("http");

const hostname = "127.0.0.1";
const port = 3000;

const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
res.end('fn({"msg":"Hello world"})');
});

server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});

image-20200822192837473

getJSON方法

1
2
3
$.getJSON('http://127.0.0.1:3000?callback=?',function(){
console.log(data);
})

调用的函数名jQuery会自动生成。

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

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

</head>

<body>
<script>
$.getJSON('http://127.0.0.1:3000?callback=?', function (data) {
console.log(data);
})
</script>

</body>

</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const http = require("http");

const hostname = "127.0.0.1";
const port = 3000;

const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
var urlObj = require("url").parse(req.url);
var functionName = urlObj.query.split("&")[0].split("=")[1];
console.log(functionName);
res.end(`${functionName}({"msg":"Hello world"})`);
});

server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});

jQuery会自动生成回调函数的名称。