Fork me on GitHub

m-通信

通信

同源策略及限制

概念:同源策略限制从一个源文件或者脚本如何与另一个源的资源进行交互,是一个用于隔离潜在恶意文件的安全机制。
跨域存在的原因:浏览器同源策略,不允许访问非同源的页面。为了保证用户信息安全,防止恶意的网站窃取数据。
同源:协议相同,域名相同,端口相同

  1. CookielocalStorageindexDB等无法读取
  2. 无法获取操作DOM
  3. AJAX请求不能发送

前后端如何通信

Ajax–>只适合同源通信
WebSocket–>不受同源策略限制
CORS–>最新通信标准,支持同源通信也支持跨域通信

如何创建 ajax

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
function ajax(options) {
let params = formsParams(options.data)
//兼容性
let xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
//请求类型
if (options.type === 'GET') {
xhr.open(options.type, options.url + '?' + params, options.async);
xhr.send(null)
} else if (options.type === 'POST') {
xhr.open(options.type, options.url, options.async);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(params)
}
xhr.onload = function () {
//成功 片段请求206
if (xhr.status === 200 || xhr.status === 304||xhr.status===206) {
var res;
if (options.success && options.success instanceof Function) {
res = xhr.responseText;
if (typeof res === 'string') {
res = JSON.parse(res);
options.success.call(xhr, res)
}
}
} else {
//失败
if (options.error && options.error instanceof Function) {
options.error.call(xhr, res)
}
}
}
//请求数据处理
function formsParams(data) {
var arr = [];
for (var prop in data) {
arr.push(prop + "=" + data[prop]);
}
return arr.join("&");
}
}
ajax({
url: "/price", // url---->地址
type: "GET", // type ---> 请求方式
async: true, // async----> 同步:false,异步:true
data: { //传入信息
name: "张三",
age: 18
},
success: function (data) { //返回接受信息
console.log(data);
},
error: function (err) {
console.log(err)
}
})

跨域

参考:https://mp.weixin.qq.com/s/g6_-IU0HHP4rfFytFFHmdA
参考:前端的网络请求方式

-------------本文结束感谢阅读-------------