Axios文章链接:一文带你理清Axios的有关问题-CSDN博客
Fetch
是浏览器原生提供的用于进行网络请求的 API,它可以用来替代传统的 XMLHttpRequest
,并且支持 Promise
,使得代码更加简洁。与 Axios
类似,你可以使用 Fetch
发送 GET
、POST
、PUT
、DELETE
等请求。下面我会详细讲解 Fetch
的基本用法及其特点。
1. 发送 GET 请求
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // 解析 JSON 响应
})
.then(data => {
console.log('Data received:', data); // 处理成功的响应数据
})
.catch(error => {
console.error('Fetch error:', error); // 处理错误
});
URL 查询参数
查询参数通常附加在 URL 的末尾,格式为 ?key1=value1&key2=value2
,多个参数用 &
连接。
2. 发送 POST 请求
当你想发送数据到服务器时,通常会使用 POST
请求。你需要在请求中指定请求方法和请求体。
fetch('https://api.example.com/login', {
method: 'POST', // 请求方法
headers: {
'Content-Type': 'application/json', // 设置请求头,告诉服务器请求体是JSON格式
},
body: JSON.stringify({
username: 'john_doe',
password: 'password123',
}),
})
.then(response => {
if (!response.ok) {
throw new Error('Login failed');
}
return response.json();
})
.then(data => {
console.log('Login successful:', data); // 处理成功的登录响应
})
.catch(error => {
console.error('Fetch error:', error);
});
3. PUT 请求
PUT
请求通常用于更新服务器上的资源。
fetch('https://api.example.com/users/1', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: 'John Doe',
age: 30
}),
})
.then(response => response.json())
.then(data => {
console.log('Update successful:', data);
})
.catch(error => {
console.error('Fetch error:', error);
});
PUT
请求的结构与 POST
类似,唯一的不同是方法名,这里是 PUT
,用于更新资源。
4. DELETE 请求
fetch('https://api.example.com/users/1', {
method: 'DELETE',
})
.then(response => {
if (!response.ok) {
throw new Error('Delete failed');
}
console.log('User deleted');
})
.catch(error => {
console.error('Fetch error:', error);
});
5. 使用 async/await
语法
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log('Data received:', data);
} catch (error) {
console.error('Fetch error:', error);
}
}
fetchData();