import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'; // 创建 Axios 实例 const service: AxiosInstance = axios.create({ baseURL: '/api', // 可根据实际情况修改 timeout: 5000 // 请求超时时间 }); // 请求拦截器 service.interceptors.request.use( (config: AxiosRequestConfig) => { // 在发送请求之前做些什么,例如添加 token // const token = localStorage.getItem('token'); // if (token) { // config.headers.Authorization = `Bearer ${token}`; // } return config; }, (error: any) => { // 处理请求错误 console.log(error); return Promise.reject(error); } ); // 响应拦截器 service.interceptors.response.use( (response: AxiosResponse) => { // 对响应数据做点什么 const res = response.data; return res; }, (error: any) => { // 处理响应错误 console.log('err' + error); return Promise.reject(error); } ); // 封装请求方法 const request = { get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> { return service.get(url, config); }, post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> { return service.post(url, data, config); }, put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> { return service.put(url, data, config); }, delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> { return service.delete(url, config); } }; export default request;
使用示例
<template> <div> <button @click="fetchData">获取数据</button> <div v-if="data">{{ data }}</div> </div> </template> <script lang="ts" setup> import { ref } from 'vue'; import request from './request'; const data = ref<any | null>(null); const fetchData = async () => { try { const result = await request.get('/test'); data.value = result; } catch (error) { console.error('请求出错:', error); } }; </script>