1. 安装axios
使用npm进行安装
npm install axios
或者yarn进行安装
yarn add axios
2. 创建axios实例并封装post和get方法
新建一个文件夹utils,并在其下面创建一个文件request.js文件,将下面代码复制到这个文件

import axios from 'axios';// 创建axios实例
const http = axios.create({baseURL: 'https://api.example.com', // API的基础路径timeout: 10000, // 请求超时时间
});// 请求拦截器
http.interceptors.request.use(config => {// 在发送请求之前做些什么,比如设置token等// config.headers.Authorization = `Bearer ${token}`;return config;},error => {// 对请求错误做些什么return Promise.reject(error);}
);// 响应拦截器
http.interceptors.response.use(response => {// 对响应数据做点什么return response.data; // 根据你的实际需求可能不需要这一行,看后端返回的数据结构而定},error => {// 对响应错误做点什么return Promise.reject(error);}
);// 封装post方法
const post = (url, data = {}, config = {}) => {return http.post(url, data, config);
};// 封装get方法
const get = (url, params = {}, config = {}) => {return http.get(url, { params, ...config }); // 使用params而不是直接将params合并到url上,以保持URL的可读性并避免某些浏览器对URL长度的限制。
};export { post, get }; // 导出post和get方法供其他文件使用。

3. 使用 ,在需要使用的页面引入,并按以下方式进行使用
import { post, get } from './path/to/your/http'; // 导入封装的http方法。注意替换为你的实际路径。// 使用post方法发送数据到服务器
post('/users', { name: 'John', age: 30 }).then(response => {console.log(response); // 处理响应数据}).catch(error => {console.error(error); // 处理错误情况});// 使用get方法从服务器获取数据
get('/users/1').then(response => {console.log(response); // 处理响应数据}).catch(error => {console.error(error); // 处理错误情况});
ok啦!
