Fetch / Axios學習:入門教程與實戰指南
本文详细介绍了Fetch与Axios学习,包括两者的定义、特点和区别,并深入讲解了它们的基本用法和高级用法,如发送GET和POST请求、处理响应和错误。通过实战案例和常见问题解决方案,帮助读者更好地理解和应用Fetch / Axios学习。
Fetch与Axios简介
什么是Fetch
Fetch是浏览器内置的一个API,用于从服务器获取数据。它基于Promise,可以处理异步操作,并支持多种HTTP方法,如GET、POST、PUT等。Fetch API提供了一种更现代的方法来处理网络请求,它更简洁、更易于使用。
什么是Axios
Axios是基于Promise的HTTP客户端,可以在浏览器和Node.js中使用。它简化了请求的发送过程,并支持拦截请求和响应、处理跨域请求(CORS)、自动转换JSON数据等特性。Axios提供了更丰富的功能和更好的错误处理机制。
Fetch与Axios的区别
特性 | Fetch | Axios |
---|---|---|
支持环境 | 浏览器、Node.js(需polyfill) | 浏览器、Node.js |
基础特性 | 基于Fetch API,支持Promise | 基于XMLHttpRequest,支持Promise |
跨域请求 | 支持CORS | 支持CORS |
JSON处理 | 需要手动解析JSON | 自动转换JSON |
拦截请求/响应 | 不支持 | 支持 |
错误处理 | 基于Promise,需要手动处理 | 有丰富的错误处理机制 |
扩展性 | 较弱 | 较强,可通过插件增强 |
使用场景 | 简单的网络请求 | 复杂的网络请求,企业级项目 |
Fetch的基本用法
发送GET请求
发送GET请求是最基本的操作。Fetch API使用fetch(url)
方法发送GET请求。该方法返回一个Promise,该Promise在成功接收到响应时解析为一个响应对象,否则在接收到一个网络错误时被拒绝。
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
发送POST请求
发送POST请求需要使用fetch(url, options)
方法。options
对象包含请求的详细信息,如请求方法、请求头、请求体等。
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username: 'John Doe', password: 'secret' })
};
fetch('https://api.example.com/login', options)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
处理响应
Fetch API的响应是一个可读的流,可以通过response.json()
方法将响应体解析为JSON对象。同样,response.text()
或response.blob()
方法可以分别将响应体解析为文本或二进制数据。
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
Axios的基本用法
发送GET请求
Axios使用.get(url)
方法发送GET请求。该方法返回一个Promise,该Promise在成功接收到响应时解析为一个响应对象,否则被拒绝。
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Axios error:', error);
});
发送POST请求
Axios使用.post(url, data)
方法发送POST请求。第一个参数是请求的URL,第二个参数是请求体数据。
const postData = {
username: 'John Doe',
password: 'secret'
};
axios.post('https://api.example.com/login', postData)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Axios error:', error);
});
处理响应
Axios的响应对象包含data
、status
、headers
等属性,可以直接访问这些属性来获取响应信息。
axios.get('https://api.example.com/data')
.then(response => {
console.log('Data:', response.data);
console.log('Status:', response.status);
console.log('Headers:', response.headers);
})
.catch(error => {
console.error('Axios error:', error);
});
Fetch与Axios的高级用法
添加请求头
在发送请求时,可以通过options
对象添加请求头信息。
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your_token_here'
},
body: JSON.stringify({ username: 'John Doe', password: 'secret' })
};
fetch('https://api.example.com/login', options)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
Axios中添加请求头同样通过配置对象。
axios.post('https://api.example.com/login', {
username: 'John Doe',
password: 'secret'
}, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your_token_here'
}
})
.then(response => console.log(response.data))
.catch(error => console.error('Axios error:', error));
处理错误
Fetch API的错误可以通过Promise的catch
方法捕获。
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
Axios的错误处理机制更丰富,可以捕获详细的错误信息。
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Axios error:', error.response ? error.response.data : error.message);
});
使用配置对象
Fetch API可以通过options
对象配置请求的所有细节。
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username: 'John Doe', password: 'secret' })
};
fetch('https://api.example.com/login', options)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
Axios使用配置对象来配置请求,配置对象包含URL、请求体、请求头等。
const config = {
url: 'https://api.example.com/login',
method: 'post',
headers: {
'Content-Type': 'application/json'
},
data: {
username: 'John Doe',
password: 'secret'
}
};
axios(config)
.then(response => console.log(response.data))
.catch(error => console.error('Axios error:', error));
实战案例
使用Fetch获取天气信息
假设有一个公开的天气API,可以使用Fetch API获取天气信息。
fetch('https://api.openweathermap.org/data/2.5/weather?q=Beijing&appid=your_api_key')
.then(response => response.json())
.then(data => {
console.log('Weather:', data.weather[0].description);
})
.catch(error => console.error('Fetch error:', error));
使用Axios获取用户信息
假设有一个公开的用户API,可以使用Axios获取用户信息。
axios.get('https://api.github.com/users/octocat')
.then(response => {
console.log('User:', response.data);
})
.catch(error => console.error('Axios error:', error));
常见问题与解决方案
请求超时
当网络请求超时时,可以设置超时时间。
Fetch API可以通过AbortController
来取消请求。
const controller = new AbortController();
const signal = controller.signal;
fetch('https://api.example.com/data', { signal })
.then(response => response.json())
.then(data => console.log(data))
.catch(error => {
if (error.name === 'AbortError') {
console.log('Request was cancelled');
} else {
console.error('Fetch error:', error);
}
});
setTimeout(() => {
controller.abort();
}, 5000);
Axios可以通过配置对象中的timeout
属性设置超时时间。
axios.get('https://api.example.com/data', {
timeout: 5000
})
.then(response => console.log(response.data))
.catch(error => console.error('Axios error:', error));
CORS跨域问题
CORS(跨域资源共享)是一种安全机制,限制了从一个源加载的文档或脚本如何与来自另一个源的资源进行交互。如果服务器配置了适当的CORS头,可以允许跨域请求。
服务器可以设置Access-Control-Allow-Origin
头来允许特定源或所有源的请求。
// 服务器端代码示例
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
Axios可以通过配置对象中的withCredentials
属性设置跨域请求时是否携带凭证。
axios.get('https://api.example.com/data', {
withCredentials: true
})
.then(response => console.log(response.data))
.catch(error => console.error('Axios error:', error));
错误码解析
网络请求可能会返回各种错误码,常见的错误码包括:
- 400: Bad Request - 请求无效
- 401: Unauthorized - 未授权
- 403: Forbidden - 被禁止的请求
- 404: Not Found - 资源未找到
- 500: Internal Server Error - 服务器内部错误
- 503: Service Unavailable - 服务不可用
在处理错误时,可以根据错误码进行相应的处理。
axios.get('https://api.example.com/data')
.then(response => console.log(response.data))
.catch(error => {
console.error('Axios error:', error.response ? error.response.status : error.message);
if (error.response && error.response.status === 401) {
console.log('Please check your credentials.');
}
});
以上是Fetch和Axios的基本用法和高级用法,以及一些常见问题的解决方案。通过这些示例和代码,希望能帮助你更好地理解和使用这两个网络请求库。
共同學習,寫下你的評論
評論加載中...
作者其他優質文章