在 javascript 中发出 http 请求的方法有很多,但最流行的两种是 axios 和本机 fetch() api。在这篇文章中,我们将比较和对比这两种方法,以确定哪一种更适合不同的场景。

http 请求是与 web 应用程序中的服务器和 api 进行通信的基础。 axios 和 fetch() 都被广泛用于有效地促进这些请求。让我们深入研究它们的功能,看看它们如何叠加。
axios 是一个第三方库,它提供基于 promise 的 http 客户端来发出 http 请求。它以其简单性和灵活性而闻名,在 javascript 社区中得到广泛使用。
axios(config)
.then(response => console.log(response.data))
.catch(error => console.error('error:', error));
axios({
method: 'post',
url: 'https://api.example.com/data',
data: { key: 'value' }
})
.then(response => console.log(response.data))
.catch(error => {
if (error.response) {
console.error('server responded with:', error.response.status);
} else if (error.request) {
console.error('no response received');
} else {
console.error('error:', error.message);
}
});
fetch() 是现代 javascript 中的内置 api,所有现代浏览器都支持。它是一个异步 web api,以 promise 的形式返回数据。
首先,使用npm或yarn安装axios:
npm install axios # or yarn add axios # or pnpm install axios
您还可以通过 cdn 包含 axios:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
以下是如何使用 axios 发出 get 请求:
import axios from 'axios';
axios.get('https://example.com/api')
.then(response => console.log(response.data))
.catch(error => console.error(error));
由于 fetch() 是内置的,因此您不需要安装任何东西。以下是如何使用 fetch() 发出 get 请求:
fetch('https://example.com/api')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
fetch(url, options)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('error:', error));
fetch('https://api.example.com/data', {
method: 'post',
headers: { 'content-type': 'application/json' },
body: json.stringify({ key: 'value' })
})
.then(response => {
if (!response.ok) throw new error('http error ' + response.status);
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('error:', error));
axios:
axios.get('/api/data', { params: { name: 'alice', age: 25 } })
.then(response => { /* handle response */ })
.catch(error => { /* handle error */ });
获取:
const url = new url('/api/data');
url.searchparams.append('name', 'alice');
url.searchparams.append('age', 25);
fetch(url)
.then(response => response.json())
.then(data => { /* handle data */ })
.catch(error => { /* handle error */ });
axios:
axios.post('/api/data', { name: 'bob', age: 30 })
.then(response => { /* handle response */ })
.catch(error => { /* handle error */ });
获取:
fetch('/api/data', {
method: 'post',
headers: { 'content-type': 'application/json' },
body: json.stringify({ name: 'bob', age: 30 })
})
.then(response => response.json())
.then(data => { /* handle data */ })
.catch(error => { /* handle error */ });
axios:
axios.get('/api/data', { timeout: 5000 }) // 5 seconds
.then(response => { /* handle response */ })
.catch(error => { /* handle error */ });
获取:
const controller = new abortcontroller();
const signal = controller.signal;
settimeout(() => controller.abort(), 5000); // abort after 5 seconds
fetch('/api/data', { signal })
.then(response => response.json())
.then(data => { /* handle data */ })
.catch(error => { /* handle error */ });
axios:
async function getdata() {
try {
const response = await axios.get('/api/data');
// handle response
} catch (error) {
// handle error
}
}
获取:
async function getdata() {
try {
const response = await fetch('/api/data');
const data = await response.json();
// handle data
} catch (error) {
// handle error
}
}
axios:
获取:
axios:
处理 catch 块中的错误,并将 2xx 之外的任何状态代码视为错误:
try {
const response = await axios.get('/api/data');
// handle response
} catch (error) {
console.log(error.response.data);
}
获取:
需要手动状态检查:
try {
const response = await fetch('/api/data');
if (!response.ok) throw new Error('HTTP error ' + response.status);
const data = await response.json();
// handle data
} catch (error) {
console.log(error.message);
}
没有明确的答案,这取决于您的要求:

echoapi 是一个一体化协作 api 开发平台,提供用于设计、调试、测试和模拟 api 的工具。 echoapi 可以自动生成用于发出 http 请求的 axios 代码。




axios 和 fetch() 都是在 javascript 中发出 http 请求的强大方法。选择最适合您的项目需求和偏好的一种。使用 echoapi 等工具可以增强您的开发工作流程,确保您的代码准确高效。快乐编码!
以上就是Axios 与 Fetch:哪个最适合 HTTP 请求?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号