feat: 改用alova请求

This commit is contained in:
h_mo 2023-03-29 20:07:41 +08:00
parent 0b3f5601c8
commit bb83550fe1
8 changed files with 136 additions and 57 deletions

View File

@ -4,7 +4,7 @@ VITE_ENV = development
VITE_PORT = 3000 VITE_PORT = 3000
# BASE_URL # BASE_URL
VITE_BASE_URL = https://api-catch.ranesuangyu.top VITE_BASE_URL = /api/v1
# 上传域名 # 上传域名
VITE_UPLOAD_URL = /upload VITE_UPLOAD_URL = /upload

View File

@ -2,7 +2,6 @@
VITE_ENV = production VITE_ENV = production
# api域名 # api域名
VITE_BASE_URL = https://api-catch.ranesuangyu.top VITE_BASE_URL = /api/v1
# 上传域名 # 上传域名
VITE_UPLOAD_URL = /upload VITE_UPLOAD_URL = /upload

View File

@ -37,6 +37,8 @@
"prepare": "husky install" "prepare": "husky install"
}, },
"dependencies": { "dependencies": {
"@alova/adapter-uniapp": "^1.1.1",
"@alova/mock": "^1.2.2",
"@dcloudio/uni-app": "3.0.0-alpha-3071220230324001", "@dcloudio/uni-app": "3.0.0-alpha-3071220230324001",
"@dcloudio/uni-app-plus": "3.0.0-alpha-3071220230324001", "@dcloudio/uni-app-plus": "3.0.0-alpha-3071220230324001",
"@dcloudio/uni-components": "3.0.0-alpha-3071220230324001", "@dcloudio/uni-components": "3.0.0-alpha-3071220230324001",
@ -52,10 +54,10 @@
"@dcloudio/uni-quickapp-webview": "3.0.0-alpha-3071220230324001", "@dcloudio/uni-quickapp-webview": "3.0.0-alpha-3071220230324001",
"@fortawesome/fontawesome-free": "^6.4.0", "@fortawesome/fontawesome-free": "^6.4.0",
"@iconify/iconify": "^3.1.0", "@iconify/iconify": "^3.1.0",
"alova": "^2.0.9",
"crypto-js": "^4.1.1", "crypto-js": "^4.1.1",
"echarts": "^5.4.2", "echarts": "^5.4.2",
"lodash-es": "^4.17.21", "lodash-es": "^4.17.21",
"luch-request": "^3.0.8",
"pinia": "^2.0.33", "pinia": "^2.0.33",
"qs": "^6.11.1", "qs": "^6.11.1",
"vue": "^3.2.47" "vue": "^3.2.47"

View File

@ -7,3 +7,15 @@ export enum ResultEnum {
TIMEOUT = 401, TIMEOUT = 401,
TYPE = 'success', TYPE = 'success',
} }
/**
* @description: contentType
*/
export enum ContentTypeEnum {
// json
JSON = 'application/json;charset=UTF-8',
// form-data qs
FORM_URLENCODED = 'application/x-www-form-urlencoded;charset=UTF-8',
// form-data upload
FORM_DATA = 'multipart/form-data;charset=UTF-8',
}

View File

@ -1,5 +1,7 @@
import { ResultEnum } from '@/enums/httpEnum';
declare interface API<T = any> { declare interface API<T = any> {
code: number; code: ResultEnum;
data?: T; data?: T;
message: string; message: string;
} }

View File

@ -61,7 +61,6 @@ export function isProdMode(): boolean {
* @example: * @example:
*/ */
export function getBaseUrl(): string { export function getBaseUrl(): string {
if (judgePlatform(PLATFORMS.H5) && isDevMode()) return '/api';
return getEnvValue<string>('VITE_BASE_URL'); return getEnvValue<string>('VITE_BASE_URL');
} }

View File

@ -0,0 +1,51 @@
import { Toast } from '@/utils/uniapi/prompt';
export function checkStatus(status: number, msg: string): void {
let errMessage = null;
switch (status) {
case 400:
errMessage = `${msg}`;
break;
// 401: Not logged in
// Jump to the login page if not logged in, and carry the path of the current page
// Return to the current page after successful login. This step needs to be operated on the login page.
case 401:
errMessage = '用户没有权限(令牌、用户名、密码错误)!';
break;
case 403:
errMessage = '用户得到授权,但是访问是被禁止的!';
break;
case 404:
errMessage = '网络请求错误,未找到该资源!';
break;
case 405:
errMessage = '网络请求错误,请求方法未允许!';
break;
case 408:
errMessage = '网络请求超时!';
break;
case 500:
errMessage = '服务器错误,请联系管理员!';
break;
case 501:
errMessage = '网络未实现!';
break;
case 502:
errMessage = '服务不可用,服务器暂时过载或维护!';
break;
case 503:
errMessage = '服务不可用,服务器暂时过载或维护!';
break;
case 504:
errMessage = '网络超时!';
break;
case 505:
errMessage = 'http版本不支持该请求!';
break;
default:
}
if (errMessage) {
Toast(errMessage);
}
}

View File

@ -1,65 +1,79 @@
import Request from 'luch-request'; import { createAlova } from 'alova';
import { assign } from 'lodash-es'; import AdapterUniapp from '@alova/adapter-uniapp';
import { Toast } from '@/utils/uniapi/prompt';
import { getBaseUrl } from '@/utils/env'; import { getBaseUrl } from '@/utils/env';
import { mockAdapter } from '@/mock';
import { assign } from 'lodash-es';
import { useAuthStore } from '@/state/modules/auth'; import { useAuthStore } from '@/state/modules/auth';
import { ResultEnum } from '@/enums/httpEnum'; import { checkStatus } from '@/utils/http/checkStatus';
import { ContentTypeEnum, ResultEnum } from '@/enums/httpEnum';
import { Toast } from '@/utils/uniapi/prompt';
import { API } from '@/services/model/baseModel';
const BASE_URL = getBaseUrl(); const BASE_URL = getBaseUrl();
const HEADER = { const HEADER = {
'Content-Type': 'application/json;charset=UTF-8;', 'Content-Type': ContentTypeEnum.JSON,
Accept: 'application/json, text/plain, */*', Accept: 'application/json, text/plain, */*',
}; };
function createRequest() { // @ts-ignore
return new Request({
baseURL: BASE_URL,
header: HEADER,
custom: {
auth: true,
},
});
}
const request = createRequest();
/** /**
* * alova
* @link https://github.com/alovajs/alova
*/ */
request.interceptors.request.use( const alovaInstance = createAlova({
(options) => { baseURL: BASE_URL,
if (options.custom?.auth) { ...AdapterUniapp({
const authStore = useAuthStore(); mockRequest: mockAdapter,
if (!authStore.isLogin) { }),
Toast('请先登录'); timeout: 5000,
// token不存在跳转到登录页 beforeRequest: (method) => {
return Promise.reject(options); const authStore = useAuthStore();
method.config.headers = assign(method.config.headers, HEADER, authStore.getAuthorization);
},
responsed: {
/**
*
* method实例
* @param response
* @param method
*/
onSuccess: async (response, method) => {
const { config } = method;
const { enableDownload, enableUpload } = config;
// @ts-ignore
const { statusCode, data: rawData } = response;
const { code, message, data } = rawData as API;
if (statusCode === 200) {
if (enableDownload) {
// 下载处理
return rawData;
}
if (enableUpload) {
// 上传处理
return rawData;
}
if (code === ResultEnum.SUCCESS) {
return data as any;
}
message && Toast(message);
return Promise.reject(rawData);
} }
options.header = assign(options.header, { checkStatus(statusCode, message || '');
authorization: `Bearer ${authStore.getToken}`, return Promise.reject(rawData);
}); },
}
return options;
},
(options) => Promise.reject(options)
);
/** /**
* *
*/ * method实例
request.interceptors.response.use( * @param err
async (response) => { * @param method
const { data: resData } = response; */
const { code, message } = resData; onError: (err, method) => {
if (code === ResultEnum.SUCCESS) { // error('Request Error!');
return resData as any; return Promise.reject({ err, method });
} },
Toast(message);
return Promise.reject(resData);
}, },
(response) => });
// 请求错误做点什么。可以使用async await 做异步操作
// error('Request Error!');
Promise.reject(response)
);
export { request }; export const request = alovaInstance;