123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169 |
- import axios from 'axios';
- import {uniqueSlash} from './urlUtils';
- import type {AxiosRequestConfig} from 'axios';
- import {ACCESS_TOKEN_KEY} from '@/enums/cacheEnum';
- import {Storage} from '@/utils/Storage';
- import {useUserStore} from '@/store/modules/user';
- import {alertController} from "@ionic/vue";
- // import {ExclamationCircleOutlined} from '@ant-design/icons'
- export interface RequestOptions {
- /** 当前接口权限, 不需要鉴权的接口请忽略, 格式:sys:user:add */
- permCode?: string;
- /** 是否直接获取data,而忽略message等 */
- isGetDataDirectly?: boolean;
- /** 请求成功是提示信息 */
- successMsg?: string;
- /** 请求失败是提示信息 */
- errorMsg?: string;
- /** 是否mock数据请求 */
- isMock?: boolean;
- /** 是否开发后台数据 */
- isNew?: boolean;
- isShowSuccessMsg?:boolean;
- isShowErrorMsg?:boolean;
- }
- export interface RequsetData {
- item: any;
- extdata?: any;
- success?: boolean;
- msg?: string;
- }
- const UNKNOWN_ERROR = '未知错误,请重试';
- // 是否生产环境
- // const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV);
- /** 真实请求的路径前缀 */
- const baseApiUrl = '/api/';
- /** mock请求路径前缀 */
- const baseMockUrl = '/';
- const service = axios.create({
- // baseURL: baseApiUrl,
- timeout: 120000,
- });
- service.interceptors.request.use(
- (config) => {
- const token = Storage.get(ACCESS_TOKEN_KEY);
- if (token && config.headers) {
- // 请求头token信息,请根据实际情况进行修改
- config.headers['Authorization'] = token;
- }
- return config;
- },
- (error) => {
- Promise.reject(error);
- },
- );
- service.interceptors.response.use(
- (response) => {
- const res = response.data;
- // if the custom code is not 200, it is judged as an error.
- if (res.code !== "200") {
- //$message.error(res.message || UNKNOWN_ERROR);
- // Illegal token
- if (res.code === 11001 || res.code === 11002) {
- window.localStorage.clear();
- window.location.reload();
- // to re-login
- // Modal.confirm({
- // title: '警告',
- // content: res.message || '账号异常,您可以取消停留在该页上,或重新登录',
- // okText: '重新登录',
- // cancelText: '取消',
- // onOk: () => {
- // localStorage.clear();
- // window.location.reload();
- // }
- // });
- }
- // throw other
- const error = new Error(res.message || res.msg || UNKNOWN_ERROR) as Error & { code: any,data:any };
- error.code = res.code;
- error.data=res.data;
- return Promise.reject(error);
- } else {
- return res;
- }
- },
- (error) => {
- // 处理 422 或者 500 的错误异常提示
- const errMsg = error?.response?.data?.message ?? UNKNOWN_ERROR;
- //$message.error(errMsg);
- error.message = errMsg;
- return Promise.reject(error);
- },
- );
- export type Response<T = any> = {
- code: number;
- message: string;
- data: T;
- };
- export type BaseResponse<T = any> = Promise<Response<T>>;
- /**
- *
- * @param method - request methods
- * @param url - request url
- * @param data - request data or params
- */
- export const request = async <T = any>(
- config: AxiosRequestConfig,
- options: RequestOptions = {},
- ): Promise<T> => {
- try {
- const {successMsg, errorMsg, permCode, isMock, isGetDataDirectly = true,isShowSuccessMsg = true} = options;
- // 如果当前是需要鉴权的接口 并且没有权限的话 则终止请求发起 , isNew
- if (permCode && !useUserStore().perms.includes(permCode)) {
- //return $message.error('你没有访问该接口的权限,请联系管理员!');
- return Promise.reject('你没有访问该接口的权限,请联系管理员!');
- }
- let fullUrl = '';
- fullUrl = `${(isMock ? baseMockUrl : baseApiUrl) + config.url}`;
- /*
- if (isNew) {
- fullUrl = `/n-api/${config.url}`;
- } else {
- fullUrl = `${(isMock ? baseMockUrl : baseApiUrl) + config.url}`;
- }*/
- config.url = uniqueSlash(fullUrl);
- // if (IS_PROD) {
- // // 保持api请求的协议与当前访问的站点协议一致
- // config.url.replace(/^https?:/g, location.protocol);
- // }
- const res = await service.request(config);
- successMsg && isShowSuccessMsg && presentAlert("成功",successMsg);
- //successMsg && $message.success(successMsg);
- //errorMsg && $message.error(errorMsg);
- return isGetDataDirectly ? res.data : res;
- } catch (error: any) {
- const {errorMsg,isShowErrorMsg=true} = options;
- isShowErrorMsg && presentAlert("错误",(errorMsg|| "")+error.message);
- return Promise.reject(error);
- }
- };
- const presentAlert = async (title:string,message: string) => {
- const alert = await alertController.create({
- header: title,
- message: message,
- buttons: [
- '确定'
- ],
- });
- await alert.present();
- }
|