axios.interceptors.request.use() // 開始進(jìn)行攔截請求诽嘉。
axios.interceptors.response.use()//攔截請求響應(yīng)數(shù)據(jù)。
在發(fā)送axios請求時辨萍,如果每個組件都需要各自發(fā)送的話烘跺,那么代碼太過冗余湘纵。
所以可以將請求方法進(jìn)行封裝。
創(chuàng)建ajax.js用于處理各種請求方式:
最近進(jìn)行了優(yōu)化:新增一個單獨(dú)的關(guān)于文件上傳的請求函數(shù)
import axios, {
AxiosRequestConfig,
AxiosResponse,
AxiosError
} from 'axios'
// timeout 10min
const Global_Delay = 10 * 60 * 1000;
const BASE_URL = 'http://127.0.0.1:9898/blogManage';
// 定義一個空的數(shù)組滤淳,用于存放請求中的參數(shù)
// 創(chuàng)建axios實(shí)例
const axiosInstance = () => {
const instance = axios.create({
baseURL: BASE_URL,
timeout: Global_Delay,
});
return instance;
};
// 請求實(shí)例
const publicReq = async (params: { [key: string]: any }) => {
const {
url,
method,
param
} = params;
const instance = axiosInstance();
return await instance({
url,
method,
// 在請求頭里面添加token 如果沒有則為空字符串
headers: {
'token': localStorage.getItem('token') === null ? '' : localStorage.getItem('token')
},
[method === 'post' ? 'data' : 'params']: param || {},
transformRequest: [function (data) {
let ret = ''
let index = 0;
for (let key in data) {
if (data[key] === null) {
ret += `${index === 0 ? '' : '&'}key=&`
} else {
ret += `${index === 0 ? '' : '&'}${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`
}
index += 1;
}
return ret
}]
}).then((res: AxiosResponse) => {
if (res) {
if (res.data.code === 403) {
window.location.href = "/signin";
localStorage.removeItem("name");
localStorage.removeItem("id");
localStorage.removeItem("avatar_url");
localStorage.removeItem("token")
throw new Error(res.statusText);
}
if (res.data.code !== 200) {
throw new Error(res.data.data)
} else {
return res.data;
}
}
});
};
// 請求超時函數(shù)
const timeoutfn = (delay: number, url: string) => {
return new Promise(resolve => {
setTimeout(() => {
resolve('請求超時');
}, delay);
});
};
// 單個請求 存在請求超時
export async function req(params: { [key: string]: any }, delay = Global_Delay) {
try {
const response: any = await Promise.race([
timeoutfn(delay, params.url),
publicReq(params),
]);
if (response.data.code === 401) {
localStorage.removeItem("token");
location.href = '/';
}
return response;
} catch (error) {
throw new Error(error);
}
}
// GET request
export async function getRequest(url: string, param: { [key: string]: any }) {
try {
const response = await req({
url,
method: 'get',
param,
});
return response;
} catch (err) {
console.log(err);
}
}
// POST request
export async function postRequest(url: string, param: { [key: string]: any }) {
try {
const response = await req({
url,
method: 'post',
param,
});
return response;
} catch (err) {
console.log(err);
}
}
如果模塊過多可以分文件存儲然后在index.js文件下引入向外暴露
import AdminModule from "./admin"
import ArticleModule from "./article"
import BannerModule from "./banner"
import DictionaryModule from "./dictionary"
import UploaderModule from "./uploader"
export default {
AdminModule,
ArticleModule,
BannerModule,
DictionaryModule,
UploaderModule
}