Fetch / Axios教程:新手必備的網絡請求指南
本文详细介绍了Fetch和Axios的使用方法,包括基本的GET和POST请求的发起、响应处理及错误处理。文中通过多个示例代码展示了如何在实际项目中集成Fetch和Axios,提供了完整的Fetch / Axios教程。
引入Fetch和AxiosFetch概述
Fetch API 是一个现代的、基于Promise的API,用于在浏览器中发起网络请求。Fetch API 提供了一种更简单、更一致的方式来处理网络请求。Fetch API 的核心是两个全局方法:fetch()
和 Headers
。fetch()
方法发起一个网络请求并返回一个 Promise,该 Promise 解析为一个 Response 对象,该对象包含了来自服务器的响应。
Axios概述
Axios 是一个基于Promise的HTTP库,可以用于浏览器和 Node.js 中发起网络请求。Axios 提供了更强大的错误处理机制,支持请求和响应拦截器,支持取消请求和自动转换 JSON 数据等功能。Axios 的使用更加灵活且易于上手。
如何安装Axios
为了在项目中使用 Axios,首先需要通过 npm 或 yarn 安装 Axios。以下是安装步骤:
# 使用 npm 安装 Axios
npm install axios
# 或者使用 yarn 安装 Axios
yarn add axios
安装完成后,你可以在你的 JavaScript 文件中通过 import
或 require
来引入 Axios。
// 使用 import 语法
import axios from 'axios';
// 或者使用 require 语法
const axios = require('axios');
基本的GET请求
使用Fetch发起GET请求
Fetch API 提供了 fetch
函数来发起网络请求。发起一个 GET 请求非常简单,只需要调用 fetch
函数并传入 URL 即可。fetch
函数返回一个 Promise,该 Promise 解析为一个 Response 对象,通常我们使用 response.json()
将 Response 转换为 JSON 格式的数据。
示例代码:
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('There was an error!', error);
});
使用Axios发起GET请求
Axios 提供了一个简单的 get
方法来发起 GET 请求。get
方法同样返回一个 Promise,该 Promise 成功解析为响应数据。
示例代码:
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('There was an error!', error);
});
基本的POST请求
使用Fetch发起POST请求
发起 POST 请求时,可以通过 fetch
函数配合 FormData
或 JSON.stringify
来发送数据。你可以通过设置请求头 Content-Type
来指示数据格式。
示例代码:
const data = {
key: 'value'
};
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(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('There was an error!', error);
});
使用Axios发起POST请求
Axios 支持通过传递一个配置对象来发起 POST 请求,该对象中可以包含 data
属性来指定发送的数据。
示例代码:
const data = {
key: 'value'
};
axios.post('https://api.example.com/data', data)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('There was an error!', error);
});
处理响应数据
Fetch的Promise处理
Fetch API 返回的 Promise 解析为一个 Response 对象,可以通过 response.json()
将其转换为 JSON 格式的数据。这种方式使用了 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('There was an error!', error);
});
Axios的回调处理
Axios 的 then
方法可以捕获到响应的数据和状态,同时也支持通过 catch
方法来处理错误。Axios 的响应对象包含了 data
、status
、statusText
等属性,可以直接访问这些属性来处理响应数据。
示例代码:
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('There was an error!', error);
});
错误处理
Fetch中的错误处理
在 Fetch API 中,错误处理通常通过 Promise 的 catch
方法来实现。如果响应状态码不在 200-299 之间,或者在解析过程中遇到错误,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('There was an error!', error);
});
Axios中的错误处理
Axios 提供了更强大的错误处理机制,错误会在 catch
方法中被捕获。Axios 的错误对象包含了 message
、config
和 response
等属性,可以方便地访问这些属性来处理错误。
示例代码:
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('There was an error!', error);
});
实际应用案例
Fetch和Axios的简单项目集成
假设我们正在开发一个简单的博客应用,需要从后端 API 获取文章列表和发表新文章。我们将使用 Fetch 和 Axios 分别实现这些功能。
使用Fetch获取文章列表
在此示例中,我们将使用 Fetch API 从后端 API 获取文章列表,并将这些文章显示在一个 HTML 列表中。
示例代码:
<!DOCTYPE html>
<html>
<head>
<title>博客文章列表</title>
</head>
<body>
<ul id="articlesList"></ul>
<script>
fetch('https://api.example.com/articles')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
const articlesList = document.getElementById('articlesList');
data.articles.forEach(article => {
const li = document.createElement('li');
li.textContent = article.title;
articlesList.appendChild(li);
});
})
.catch(error => {
console.error('There was an error!', error);
});
</script>
</body>
</html>
使用Axios发表新文章
此示例中,我们将使用 Axios 向后端 API 发表新文章,并在成功发表后显示一条确认消息。
示例代码:
<!DOCTYPE html>
<html>
<head>
<title>发表新文章</title>
</head>
<body>
<form id="articleForm">
<input type="text" id="title" placeholder="文章标题" required>
<textarea id="content" placeholder="文章内容" required></textarea>
<button type="submit">发表文章</button>
</form>
<div id="confirmation"></div>
<script>
const form = document.getElementById('articleForm');
const confirmation = document.getElementById('confirmation');
form.addEventListener('submit', (event) => {
event.preventDefault();
const title = document.getElementById('title').value;
const content = document.getElementById('content').value;
axios.post('https://api.example.com/articles', { title, content })
.then(response => {
confirmation.textContent = '文章发表成功!';
})
.catch(error => {
confirmation.textContent = '文章发表失败!';
console.error('There was an error!', error);
});
});
</script>
</body>
</html>
通过这些示例代码,你可以看到 Fetch 和 Axios 在实际项目中的应用,以及如何使用它们来处理网络请求和响应数据。这些示例可以帮助你更好地理解如何在实际开发中使用 Fetch 和 Axios。
共同學習,寫下你的評論
評論加載中...
作者其他優質文章