网络请求方式总结
Youky ... 2021-10-11 About 1 min
# 网络请求方式总结
# XHR
早期的原生请求对象,通过回调函数判断请求状态
const xhr = new XMLHttpRequest();
xhr.open("GET", "http://foo.com");
xhr.send();
xhr.onreadystatechange = () => {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
XHR 请求允许终止
xhr.abort();
1
# fetch
全新的底层 API,用于替代 xhr。
// promise写法
fetch("http://bar.com", {
body: JSON.stringify(data), // must match 'Content-Type' header
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, same-origin, *omit
headers: {
"user-agent": "Mozilla/4.0 MDN Example",
"content-type": "application/json",
},
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, cors, *same-origin
redirect: "follow", // manual, *follow, error
referrer: "no-referrer", // *client, no-referrer
})
.then((res) => res.json())
.then((res) => console.log(res));
// async await写法
async function request(url) {
const temp = await fetch(url);
const data = temp.json();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
和ajax
的区别:
fetch
不会根据状态码来判断请求是否成功,即使是 404 也会进入resolve状态。只有在网络故障或请求被阻止时才会进入reject。fetch
支持跨域(mode: 'cors'
)- 默认不携带 cookie。通过设置
credentials
来改变 - 不可中断请求(abort)
# jQuery.$ajax
对 xhr 的一种封装,并对于不支持 xhr 的浏览器提供了降级处理(使用 ActiveXObject 作为替代)。
提供了 get、post 等方法,简化了请求操作。并支持了 JSONP,可以简单处理部分跨域。
# axios
也是对原生 xhr 的封装,但是基于Promise
形式实现,符合最新的 ES 规范。
也支持取消请求。