AXIOS应用与封装
Axios 是一个基于 Promise 的 HTTP 客户端,用于在浏览器和 Node.js 中发送 HTTP 请求。它以其简单的 API 和强大的功能广泛应用于前端开发,特别是与 Vue.js、React 等框架搭配使用。
Axios 的主要特点
1. 支持多种运行环境
- 浏览器环境:基于 XMLHttpRequest。(ajax)
- Node.js 环境:使用
http
模块。
2. 支持 Promise API
-
Axios 的请求和响应都使用 Promise 进行封装,支持
.then
和async/await
的写法,非常适合现代 JavaScript 编程风格。javascript复制代码axios.get('/api/data') .then(response => console.log(response)) .catch(error => console.error(error));
或者使用
async/await
:const fetchData = async () => { try { const response = await axios.get('/api/data'); console.log(response.data); } catch (error) { console.error(error); } };
3. 支持请求和响应拦截器
-
拦截器可以在请求或响应发送前进行处理,例如添加认证 token 或统一处理错误。
axios.interceptors.request.use(config => { config.headers.Authorization = 'Bearer token'; return config; }); axios.interceptors.response.use( response => response, error => { console.error('Response error:', error); return Promise.reject(error); } );
4. 自动处理 JSON 数据
-
Axios 默认会对请求数据进行 JSON 编码,并自动解析 JSON 响应。
axios.post('/api/data', { key: 'value' }) // 自动序列化为 JSON .then(response => console.log(response.data)); // 自动解析 JSON
5. 支持取消请求
-
Axios 支持使用
AbortController
或其内置的CancelToken
(已废弃)来取消请求。const controller = new AbortController(); axios.get('/api/data', { signal: controller.signal }) .catch(error => console.log('Request canceled', error)); controller.abort(); // 取消请求
6. 支持请求超时
-
可以设置请求超时时间,当请求超过指定时间未完成时会自动中断。
axios.get('/api/data', { timeout: 5000 }) // 设置 5 秒超时 .catch(error => console.log('Request timed out', error));
7. 支持跨域请求
-
可以自动发送
withCredentials
,支持跨域场景下的 Cookie 传递。axios.get('https://api.example.com/data', { withCredentials: true });
8. 强大的配置选项
-
Axios 提供了灵活的全局配置和实例配置功能,可根据不同场景定制请求行为。
-
全局配置
:
axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = 'Bearer token';
-
实例配置
:
const instance = axios.create({ baseURL: 'https://api.example.com', timeout: 1000, });
-
9. 支持上传和下载进度监控
-
可通过
onUploadProgress
和onDownloadProgress
回调监控文件上传和下载的进度。axios.post('/upload', file, { onUploadProgress: progressEvent => { console.log(`Uploaded: ${(progressEvent.loaded / progressEvent.total) * 100}%`); } });
10. 支持多种请求方式
-
支持
GET
、POST
、PUT
、DELETE
、PATCH
等常用的 HTTP 请求方法。javascript复制代码axios.post('/api/data', { key: 'value' }); axios.put('/api/data/1', { key: 'newValue' }); axios.delete('/api/data/1');
axios安装
npm install axios
json-server
简介
json-server 可以让前端人员不用去编写后端的代码,就能在本地搭建一个 json 服务,可用于测试一些业务逻辑,便于调试调用。
在前后端分离的开发模式下前端使用 json-server 模拟数据接口, 这时候 后端接口还没有开发出来, 前端又需要数据进行开发,这种情况下就需要前端先行模拟数据, 等后端接口写好进行 targetUrl 进行替换。
搭建http服务
1.安装json_server(json格式)
npm install -g json-server
2.使用
①创建本地数据源(文件名db.json)
{
"users": [
{
"id": "1",
"name": "Mico",
"age": 18
},
{
"id": "2",
"name": "Rose",
"age": 21
},
{
"id": "3",
"name": "Jack",
"age": 22
},
{
"id": "4",
"name": "Jon",
"age": 19
}
]
}
②启动Json—server
json-server --watch db.json
此处一定要在db.json文件目录下启动
访问地址
点开可以看到我们的json数据
操作数据
查询数据(GET方法)
1.查询所有数据
GET localhost:3000/users
2.根据ID查询
GET localhost:3000/users/1
3.条件查询
GET localhost:3000/users?age=22
4.分页查询
GET localhost:3000/users?_page=1&_limit=2
新增数据(post)
POST localhost:3000/users
修改数据(PUT)
PUT localhost:3000/users/3
删除数据(DELETE)
DELETE localhost:3000/users/3
GET:获取资源。
POST:创建资源或提交数据。
PUT:更新资源。
DELETE:删除资源。
例子
<template>
<button v-on:click="bt1">
发送get请求
</button>
</template>
<script lang="ts">
export default {
name: 'request'
}
</script>
<script setup lang="ts" >
import axios from 'axios'
function bt1(){
1.基于promise的写法
axios.get('http://localhost:3000/users')
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
})
}
2.vue3的写法(使用 async/await 语法来代替回调式的 .then() 和 .catch())
const bt1 = async () => {
try {
const response = await axios.get('http://localhost:3000/users');
console.log(response.data); // 直接打印返回的数据
} catch (err) {
console.log(err); // 错误处理
}
};
</script>
vue3的写法
<template>
<button @click="bt1">发送 GET 请求</button>
</template>
<script setup lang="ts">
import axios from 'axios';
// 发送 GET 请求的方法
const bt1 = async () => {
try {
const response = await axios.get('http://localhost:3000/users');
console.log(response.data); // 直接打印返回的数据
} catch (err) {
console.log(err); // 错误处理
}
};
</script>
<style scoped>
/* 样式 */
</style>
查看控制台
axios封装
1.创建axios实例
// src/utils/axios.ts
import axios, { AxiosInstance } from 'axios';
// 创建 axios 实例
const instance: AxiosInstance = axios.create({
baseURL: 'http://localhost:3000', // 设置 API 的基础 URL
timeout: 5000, // 请求超时时间,单位:ms
});
// 请求拦截器(例如加入 token 等)
instance.interceptors.request.use(
(config) => {
// 假设我们从 localStorage 获取 token
const token = localStorage.getItem('token');
if (token) {
config.headers['Authorization'] = `Bearer ${token}`; // 设置 Authorization 头
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
// 响应拦截器
instance.interceptors.response.use(
(response) => {
return response.data; // 直接返回数据部分
},
(error) => {
// 处理错误,比如弹出提示框等
if (error.response?.status === 401) {
alert('未授权,请重新登录');
// 这里可以跳转到登录页或做其他处理
}
return Promise.reject(error); // 抛出错误
}
);
export default instance;
2.封装函数
// src/services/api.ts
import axios from '../utils/axios';
export const getUsers = async () => {
try {
const response = await axios.get('/users/1');
// 确保返回的是 users 数组
return response // 从 response 中提取 users 数组
} catch (error) {
throw error;
}
};
3.函数调用
<template>
<div>
<button @click="bt1">发送 GET 请求</button>
<div v-if="loading">加载中...</div>
<div v-if="error">{{ error }}</div>
<ul v-if="!loading && users?.length">
<li v-for="user in users" :key="user.id">{{ user.name }}</li>
</ul>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { getUsers } from '../../../../services/api'; // 引入封装好的 API 请求
const users = ref<any[]>([]);
const loading = ref(false);
const error = ref<string | null>(null);
const bt1 = async () => {
loading.value = true;
error.value = null;
try {
// 调用封装好的 GET 请求函数,获取用户数组
const users = await getUsers();
console.log(users);
} catch (err) {
error.value = '请求失败'; // 错误处理
console.log(err);
} finally {
loading.value = false;
}
};
</script>
<style scoped>
/* 样式 */
</style>
const error = ref<string | null>(null);
const bt1 = async () => {
loading.value = true;
error.value = null;
try {
// 调用封装好的 GET 请求函数,获取用户数组
const users = await getUsers();
console.log(users);
} catch (err) {
error.value = '请求失败'; // 错误处理
console.log(err);
} finally {
loading.value = false;
}
};