Fetch

前言:就像我之前所说的,由于发现了自己在网络方面的知识不足,所以决定充充电,发现除了Ajax之外还有Fetch这么一个东西


1.什么是Fetch

Fetch API 提供了一个 JavaScript 接口,用于访问和操纵 HTTP 管道的一些具体部分,例如请求和响应。它还提供了一个全局 fetch() 方法,该方法提供了一种简单,合理的方式来跨网络异步获取资源。

这种功能以前是使用 XMLHttpRequest 实现的。Fetch 提供了一个更理想的替代方案,可以很容易地被其他技术使用,例如  [Service Workers]。

2.Fetch与jquery.ajax的不同

1)如果Fetch返回的http状态码为400或者500,也就是代表错误的http状态码的情况下, 返回的 Promise 不会被标记为 reject,只有在当网络故障时或请求被阻止时,才会标记为 reject。

2)fetch()可以不会接受跨域 cookies;**你也可以不能使用 fetch() 建立起跨域会话。其他网站的 [Set-Cookie](https://wiki.developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie) 头部字段将会被无视。

3)fetch 不会发送 cookies。除非你使用了credentials 的初始化选项

3.基本的Fetch使用

简单的GET请求

1
2
3
4
5
6
7
fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});

简单的POST请求

1
2
3
4
fetch('https://www.easy-mock.com/mock/5ca59ba44ba86c23d507bd40/example/getUser',{method:"post"})
.then(resp=>resp.json()) //转换成Json对象
.then(resp=>console.log(resp)) //输出Json内容
.catch(error => console.error(error));

第二个参数

一个可以控制不同配置的 init 对象

上传JSON数据

1
2
3
4
5
6
7
8
9
10
11
12
var url = 'https://example.com/profile';
var data = {username: 'example'};

fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(data), // data can be `string` or {object}!
headers: new Headers({
'Content-Type': 'application/json'
})
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));

上传文件

1
2
3
4
5
6
7
8
9
10
11
12
13
var formData = new FormData();
var fileField = document.querySelector("input[type='file']");

formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);

fetch('https://example.com/profile/avatar', {
method: 'PUT',
body: formData
})
.then(response => response.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));

4.高级的Fetch使用

超时设置

1
2
3
4
5
6
7
8
9
10
11
12
13
var formData = new FormData();
var fileField = document.querySelector("input[type='file']");

formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);

fetch('https://example.com/profile/avatar', {
method: 'PUT',
body: formData
})
.then(response => response.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));

5.取消请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
let controller = new AbortController();
let signal = controller.signal;

let timeoutPromise = (timeout) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(new Response("timeout", { status: 504, statusText: "timeout " }));
controller.abort();
}, timeout);
});
}
let requestPromise = (url) => {
return fetch(url, {
signal: signal
});
};
Promise.race([timeoutPromise(1000), requestPromise("https://www.baidu.com")])
.then(resp => {
console.log(resp);
})
.catch(error => {
console.log(error);
});

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!