主题
使用 Fetch 与 Axios 请求数据
在 React 中,进行数据请求是常见的操作。你可以使用原生的 fetch
API 或者流行的第三方库 Axios
来发送 HTTP 请求。下面我们将分别介绍如何使用这两者进行数据请求。
1. 使用 Fetch 发送请求
fetch
是浏览器原生支持的 API,适用于发送各种类型的 HTTP 请求。它返回一个 Promise,因此可以通过 .then()
或 async/await
进行处理。
基本用法
jsx
import { useState, useEffect } from 'react';
function FetchExample() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
setData(data);
setLoading(false);
})
.catch(error => console.error('Error fetching data:', error));
}, []);
if (loading) {
return <div>Loading...</div>;
}
return <div>{JSON.stringify(data)}</div>;
}
错误处理
fetch
默认不会抛出 HTTP 错误状态(如 404 或 500),你需要手动检查 response.ok
来处理错误。
jsx
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => setData(data))
.catch(error => console.error('Fetch error:', error));
2. 使用 Axios 发送请求
Axios
是一个基于 Promise 的 HTTP 客户端,可以在浏览器和 Node.js 中使用。它提供了更友好的 API 和内置的请求/响应拦截功能,常用于发送 HTTP 请求。
安装 Axios
首先,你需要安装 Axios
:
bash
npm install axios
基本用法
jsx
import { useState, useEffect } from 'react';
import axios from 'axios';
function AxiosExample() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
axios.get('https://api.example.com/data')
.then(response => {
setData(response.data);
setLoading(false);
})
.catch(error => console.error('Error fetching data:', error));
}, []);
if (loading) {
return <div>Loading...</div>;
}
return <div>{JSON.stringify(data)}</div>;
}
错误处理
Axios
会自动处理 HTTP 错误状态码,你可以直接在 .catch()
中捕获和处理。
jsx
axios.get('https://api.example.com/data')
.then(response => setData(response.data))
.catch(error => {
if (error.response) {
// 请求已发出,但服务器响应的状态码超出了 2xx 的范围
console.error('Response error:', error.response);
} else if (error.request) {
// 请求已发出,但没有收到响应
console.error('No response:', error.request);
} else {
// 其他错误
console.error('Axios error:', error.message);
}
});
配置请求
Axios
还允许你在请求中设置很多配置项,如请求头、超时等。
jsx
axios.get('https://api.example.com/data', {
headers: {
'Authorization': 'Bearer token'
},
timeout: 5000
})
.then(response => setData(response.data))
.catch(error => console.error('Error:', error));
3. 总结
fetch
是一个内建的 API,适用于简单的 HTTP 请求,使用时需要手动处理一些细节(如错误状态码)。Axios
提供了更丰富的功能和易用的 API,自动处理错误,并支持请求和响应拦截,适合更复杂的需求。
两者各有优势,选择哪种方式取决于你的项目需求和个人偏好。