一、安裝axios
npm install axios @types/axios --save
二、配置代理vite.config.ts,如果沒有需要新建該文件
module.exports = {
server: {
proxy: {
'/api': {
target: 'http://localhost:5000', // 設(shè)置代理目標(biāo)
changeOrigin: true, // 是否改變請(qǐng)求源地址
rewrite: (path) => path.replace(/^\/api/, '') // 將 /api 替換為空字符串
}
}
}
};
三、新建utils文件夾,在utils文件夾下新建http.ts文件和methods.ts,如圖:
http.ts文件內(nèi)容:
import axios from 'axios';
import type { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';
// 創(chuàng)建axios實(shí)例
const instance = axios.create({
baseURL: '/api', // 設(shè)置API的基礎(chǔ)URL
});
// 請(qǐng)求攔截器
instance.interceptors.request.use(
(config: AxiosRequestConfig):any => {
// 可在請(qǐng)求發(fā)送前對(duì)config進(jìn)行修改,如添加請(qǐng)求頭等
const headers = config.headers || {};
headers['Authorization'] = 'Bxxx';
config.headers = headers;
return config;
},
(error: AxiosError) => {
// 處理請(qǐng)求錯(cuò)誤
return Promise.reject(error);
}
);
// 響應(yīng)攔截器
instance.interceptors.response.use(
(response: AxiosResponse) => {
// 對(duì)響應(yīng)數(shù)據(jù)進(jìn)行處理
return response;
},
(error: AxiosError) => {
// 處理響應(yīng)錯(cuò)誤
return Promise.reject(error);
}
);
export default instance
methods.ts文件內(nèi)容:
import instance from './http'
// 封裝GET請(qǐng)求
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請(qǐng)求
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文件夾,用于存放接口 結(jié)構(gòu)如下
api/user.ts 用戶相關(guān)接口
import { get } from '@/utils/methods'
import type { UserRequest } from '../types/user.d'
export function userRequest(params: UserRequest) {
return get('/users', { params }); //測(cè)試接口
}
types/user.d.ts定義接口ts類型
export interface UserRequest{
pageNum?:number,
pageSize?:number,
}
五、在vue文件中使用
<script setup lang="ts">
// 導(dǎo)出指定模塊
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>
文章來源:http://www.zghlxwxcb.cn/news/detail-783126.html
請(qǐng)求成功測(cè)試文章來源地址http://www.zghlxwxcb.cn/news/detail-783126.html
到了這里,關(guān)于vue3+ts+vite中封裝axios,使用方法從0到1的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!