使用umi框架是,網(wǎng)絡(luò)請求用自帶的request進行二次封裝,核心代碼如下。直接放在src下的app.js中即可
const codeMessage = {
200: '服務(wù)器成功返回請求的數(shù)據(jù)。',
201: '新建或修改數(shù)據(jù)成功。',
202: '一個請求已經(jīng)進入后臺排隊(異步任務(wù))。',
204: '刪除數(shù)據(jù)成功。',
400: '發(fā)出的請求有錯誤,服務(wù)器沒有進行新建或修改數(shù)據(jù)的操作。',
401: '用戶沒有權(quán)限(令牌、用戶名、密碼錯誤)。',
403: '用戶得到授權(quán),但是訪問是被禁止的。',
404: '發(fā)出的請求針對的是不存在的記錄,服務(wù)器沒有進行操作。',
405: '請求方法不被允許。',
406: '請求的格式不可得。',
410: '請求的資源被永久刪除,且不會再得到的。',
422: '當創(chuàng)建一個對象時,發(fā)生一個驗證錯誤。',
500: '服務(wù)器發(fā)生錯誤,請檢查服務(wù)器。',
502: '網(wǎng)關(guān)錯誤。',
503: '服務(wù)不可用,服務(wù)器暫時過載或維護。',
504: '網(wǎng)關(guān)超時。',
};
// 全局請求
const requestInterceptor = (url, options) => {
return {
url: 'http://localhost:3009' + url, // 此處可以添加域名前綴
options: {
...options,
headers: {
authorization: 'Bearer',
},
},
};
};
// 全局相應(yīng)攔截
const responseInterceptor = (response, options) => {
console.log('返回了');
return response;
};
const errorHandler = (error) => {
const { response } = error;
if (response && response.status) {
const errorText = codeMessage[response.status] || response.statusText;
const { status, url } = response;
console.log(`請求錯誤 ${status}: ${url}`);
// notification.error({
// message: `請求錯誤 ${status}: ${url}`,
// description: errorText,
// });
}
if (!response) {
// notification.error({
// description: '您的網(wǎng)絡(luò)發(fā)生異常,無法連接服務(wù)器',
// message: '網(wǎng)絡(luò)異常',
// });
}
throw error;
};
export const request = {
timeout: 1000,
errorConfig: {},
middlewares: [],
// 異常處理
errorHandler,
requestInterceptors: [requestInterceptor],
responseInterceptors: [responseInterceptor],
};