一、安装axios
javascript
npm install axios @types/axios --save
二、配置代理vite.config.ts,如果没有需要新建该文件
javascript
module.exports = {
server: {
proxy: {
'/api': {
target: 'http://localhost:5000', // 设置代理目标
changeOrigin: true, // 是否改变请求源地址
rewrite: (path) => path.replace(/^\/api/, '') // 将 /api 替换为空字符串
}
}
}
};
三、新建utils文件夹,在utils文件夹下新建http.ts文件和methods.ts,如图:
http.ts文件内容:
javascript
import axios from 'axios';
import type { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';
// 创建axios实例
const instance = axios.create({
baseURL: '/api', // 设置API的基础URL
});
// 请求拦截器
instance.interceptors.request.use(
(config: AxiosRequestConfig):any => {
// 可在请求发送前对config进行修改,如添加请求头等
const headers = config.headers || {};
headers['Authorization'] = 'Bxxx';
config.headers = headers;
return config;
},
(error: AxiosError) => {
// 处理请求错误
return Promise.reject(error);
}
);
// 响应拦截器
instance.interceptors.response.use(
(response: AxiosResponse) => {
// 对响应数据进行处理
return response;
},
(error: AxiosError) => {
// 处理响应错误
return Promise.reject(error);
}
);
export default instance
methods.ts文件内容:
javascript
import instance from './http'
// 封装GET请求
export function get<T>(url: string, params?: any): Promise<T> {
return instance.get<T>(url, { params })
.then(response => response.data)
.catch(error => {
throw error;
});
}
// 封装POST请求
export function post<T>(url: string, data?: any): Promise<T> {
return instance.post<T>(url, data)
.then(response => response.data)
.catch(error => {
throw error;
});
}
// put
export function put<T>(url: string, data?: any): Promise<T> {
return instance.put<T>(url, data)
.then(response => response.data)
.catch(error => {
throw error;
});
}
//delete
export function del<T>(url: string): Promise<T> {
return instance.delete<T>(url)
.then(response => response.data)
.catch(error => {
throw error;
});
}
四、新建api文件夹,用于存放接口 结构如下
api/user.ts 用户相关接口
javascript
import { get } from '@/utils/methods'
import type { UserRequest } from '../types/user.d'
export function userRequest(params: UserRequest) {
return get('/users', { params }); //测试接口
}
types/user.d.ts定义接口ts类型
javascript
export interface UserRequest{
pageNum?:number,
pageSize?:number,
}
五、在vue文件中使用
javascript
<script setup lang="ts">
// 导出指定模块
import useStore from '@/store'
import { onMounted } from 'vue'
import { userRequest } from '@/apis/api/user'
const { user } = useStore()
// 获取
user.getUserList()
onMounted(() => {
userRequest({}).then((res: any) => {
console.log('res: ', res)
})
})
</script>
请求成功测试