vue3+vite 封裝axios請求
安裝axios
npm install axios
創(chuàng)建axios實例
// http/index.js
import axios from 'axios'
import {
ElLoading,
ElMessage
} from 'element-plus';
//創(chuàng)建axios的一個實例
var instance = axios.create({
baseURL: import.meta.env.VITE_APP_URL, //接口統(tǒng)一域名
timeout: 6000, //設置超時
headers: {
'Content-Type': 'application/json;charset=UTF-8;',
}
})
let loading;
//正在請求的數(shù)量
let requestCount = 0
//顯示loading
const showLoading = () => {
if (requestCount === 0 && !loading) {
loading = ElLoading.service({
text: "Loading ",
background: 'rgba(0, 0, 0, 0.7)',
spinner: 'el-icon-loading',
})
}
requestCount++;
}
//隱藏loading
const hideLoading = () => {
requestCount--
if (requestCount == 0) {
loading.close()
}
}
//請求攔截器
instance.interceptors.request.use((config) => {
showLoading()
// 每次發(fā)送請求之前判斷是否存在token,如果存在,則統(tǒng)一在http請求的header都加上token,不用每次請求都手動添加了
const token = window.localStorage.getItem('token');
token && (config.headers.Authorization = token)
//若請求方式為post,則將data參數(shù)轉為JSON字符串
if (config.method === 'POST') {
config.data = JSON.stringify(config.data);
}
return config;
}, (error) =>
// 對請求錯誤做些什么
Promise.reject(error));
//響應攔截器
instance.interceptors.response.use((response) => {
hideLoading()
//響應成功
console.log('攔截器報錯');
return response.data;
}, (error) => {
console.log(error)
//響應錯誤
if(error.response&&error.response.status){
const status = error.response.status
switch (status) {
case 400:
message = '請求錯誤';
break;
case 401:
message = '請求錯誤';
break;
case 404:
message = '請求地址出錯';
break;
case 408:
message = '請求超時';
break;
case 500:
message = '服務器內部錯誤!';
break;
case 501:
message = '服務未實現(xiàn)!';
break;
case 502:
message = '網(wǎng)關錯誤!';
break;
case 503:
message = '服務不可用!';
break;
case 504:
message = '網(wǎng)關超時!';
break;
case 505:
message = 'HTTP版本不受支持';
break;
default:
message = '請求失敗'
}
ElMessage.error(message);
return Promise.reject(error);
}
return Promise.reject(error);
});
export default instance;
封裝請求方式
// http/axios.js
import instance from "./index"
/**
* @param {String} method 請求的方法:get、post、delete、put
* @param {String} url 請求的url:
* @param {Object} data 請求的參數(shù)
* @param {Object} config 請求的配置
* @returns {Promise} 返回一個promise對象,其實就相當于axios請求數(shù)據(jù)的返回值
*/
const axios = ({
method,
url,
data,
config
}) => {
method = method.toLowerCase();
if (method == 'post') {
return instance.post(url, data, {...config})
} else if (method == 'get') {
return instance.get(url, {
params: data,
...config
})
} else if (method == 'delete') {
return instance.delete(url, {
params: data,
...config
}, )
} else if (method == 'put') {
return instance.put(url, data,{...config})
} else {
console.error('未知的method' + method)
return false
}
}
封裝請求接口
創(chuàng)建api文件
import axios from "../http/request"
//請求示例
//get
export const mokeGet = (data) => {
return axios({
url: "/api/xxxx",
method: "get",
data,
config: {
headers: {
'Request-Type': 'wechat'
},
timeout: 10000
}
})
}
//post
export const mokePost = (data) => {
return axios({
url: "/api/xxxx",
method: "post",
data,
config: {
headers: {
'Request-Type': 'wechat'
},
timeout: 10000
}
})
}
vue中調用
import { mokePost } from "@/api";
import {onMounted} from "vue"
export default {
setup() {
onMounted(() => {
mokePost().then(res=>{
console.log(res)
})
})
return {};
},
};