npm install axios @types/axios --save
module.exports = {
server: {
proxy: {
'/api': {
target: 'http://localhost:5000', // 设置代理目标
changeOrigin: true, // 是否改变请求源地址
rewrite: (path) => path.replace(/^\/api/, '') // 将 /api 替换为空字符串
}
}
}
};
http.ts文件内容:
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文件内容:
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/user.ts 用户相关接口
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类型
export interface UserRequest{
pageNum?:number,
pageSize?:number,
}
<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>
请求成功测试