使用 Fetch API 变得简单——打造属于自己的 Axios
2024-01-17 18:05:06
在前端开发中,我们经常需要发送HTTP请求来获取或更新数据。传统的XMLHttpRequest(XHR)对象虽然可以胜任,但存在着许多缺陷,例如使用不方便、缺乏对Promise的支持等。因此,Fetch API作为XHR的一个替代方案而备受关注。
在本文中,我们将讨论 Fetch API 的相关内容,并提供10个使用技巧,帮助您轻松使用 Fetch API。
1. 简介
Fetch API 是一种JavaScript接口,用于跨网络异步获取资源(HTTP请求)。它比传统的XMLHttpRequest对象更容易使用,并且提供了更多的特性,例如对Promise的支持。
2. 使用 Fetch API
使用 Fetch API非常简单,只需使用fetch()
方法即可。fetch()
方法接受一个参数,即请求的URL。如果请求成功,fetch()
方法将返回一个Promise,Promise包含请求的响应对象。
fetch('https://example.com/api/users')
.then(response => response.json())
.then(data => console.log(data));
3. 技巧和实践
-
使用 async/await
使用
async/await
可以使代码更加简洁和易于阅读。
async function getUsers() {
const response = await fetch('https://example.com/api/users');
const data = await response.json();
return data;
}
-
使用 Request 对象
Request
对象允许您指定请求的各种选项,例如方法、标头、正文等。
const request = new Request('https://example.com/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: 'John Doe',
email: 'john.doe@example.com',
}),
});
fetch(request)
.then(response => response.json())
.then(data => console.log(data));
-
使用 Headers 对象
Headers
对象允许您指定请求的标头。
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', 'Bearer 123456');
const request = new Request('https://example.com/api/users', {
method: 'POST',
headers: headers,
body: JSON.stringify({
name: 'John Doe',
email: 'john.doe@example.com',
}),
});
fetch(request)
.then(response => response.json())
.then(data => console.log(data));
-
使用 Body 对象
Body
对象允许您指定请求的正文。
const body = new FormData();
body.append('name', 'John Doe');
body.append('email', 'john.doe@example.com');
const request = new Request('https://example.com/api/users', {
method: 'POST',
body: body,
});
fetch(request)
.then(response => response.json())
.then(data => console.log(data));
-
使用 Response 对象
Response
对象包含请求的响应。
fetch('https://example.com/api/users')
.then(response => {
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.body);
});
-
使用 JSON 方法
JSON
方法可以将响应的数据转换为JSON对象。
fetch('https://example.com/api/users')
.then(response => response.json())
.then(data => console.log(data));
-
使用 Blob 方法
Blob
方法可以将响应的数据转换为Blob对象。
fetch('https://example.com/api/users')
.then(response => response.blob())
.then(blob => {
// Save the blob to a file
const file = new File([blob], 'users.json');
saveAs(file);
});
-
使用 Text 方法
Text
方法可以将响应的数据转换为文本。
fetch('https://example.com/api/users')
.then(response => response.text())
.then(text => console.log(text));
-
使用 ArrayBuffer 方法
ArrayBuffer
方法可以将响应的数据转换为ArrayBuffer对象。
fetch('https://example.com/api/users')
.then(response => response.arrayBuffer())
.then(arrayBuffer => {
// Process the array buffer
const data = new Uint8Array(arrayBuffer);
console.log(data);
});
-
使用 FormData 对象
FormData
对象允许您将表单数据发送给服务器。
const form = document.querySelector('form');
form.addEventListener('submit', (event) => {
event.preventDefault();
const formData = new FormData(form);
fetch('https://example.com/api/users', {
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(data => console.log(data));
});
-
使用 Fetch API 发送自定义请求
您可以使用 Fetch API 发送自定义请求,例如DELETE、PUT和PATCH请求。
// 发送DELETE请求
fetch('https://example.com/api/users/1', {
method: 'DELETE',
})
.then(response => response.json())
.then(data => console.log(data));
// 发送PUT请求
fetch('https://example.com/api/users/1', {
method: 'PUT',
body: JSON.stringify({
name: 'John Doe',
email: 'john.doe@example.com',
}),
})
.then(response => response.json())
.then(data => console.log(data));
// 发送PATCH请求
fetch('https://example.com/api/users/1', {
method: 'PATCH',
body: JSON.stringify({
name: 'John Doe',
}),
})
.then(response => response.json())
.then(data => console.log(data));
-
使用 Fetch API 发送跨域请求
您可以使用 Fetch API 发送跨域请求,但需要在服务器端设置 CORS 头。
// 服务器端设置CORS头
Access-Control-Allow-Origin: *
// 客户端发送跨域请求
fetch('https://example.com/api/users')
.then(response => response.json())
.then(data => console.log(data));
Fetch API 是一个非常强大的工具,可以帮助您轻松发送HTTP请求。如果您正在开发前端应用程序,强烈建议您使用 Fetch API。