forked from gxwebsoft/yufengxing-pc
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
67 lines
2.2 KiB
67 lines
2.2 KiB
/**
|
|
* 参考文档
|
|
* https://blog.csdn.net/m0_63281537/article/details/126699761
|
|
*/
|
|
|
|
import { useFetch } from '#app';
|
|
import type { UseFetchOptions } from '#app';
|
|
import {isArray} from '~/utils/tool';
|
|
import {isInteger} from "~/utils/common";
|
|
|
|
export const useServerRequest = <T>(url: string, opts?: UseFetchOptions<T, unknown>) => {
|
|
// 配置信息
|
|
const runtimeConfig = useRuntimeConfig();
|
|
// 请求接口
|
|
const baseUrl = ref('');
|
|
baseUrl.value = runtimeConfig.public.apiServer;
|
|
// 开发环境
|
|
if(process.env.NODE_ENV === 'development'){
|
|
// baseUrl.value = `http://127.0.0.1:9002/api`
|
|
}
|
|
// 登录凭证token
|
|
const token = useToken();
|
|
const _token = localStorage.getItem('token');
|
|
if(_token){
|
|
token.value = _token
|
|
}
|
|
const defaultOptions: UseFetchOptions<unknown> = {
|
|
baseURL: baseUrl.value,
|
|
onRequest({ options }) {
|
|
options.headers = (options.headers || {}) as { [key: string]: string };
|
|
if(process.env.NODE_ENV === 'development') {
|
|
options.headers.tenantid = `${runtimeConfig.public.tenantId}`;
|
|
}
|
|
if (token.value) {
|
|
options.headers.Authorization = token.value;
|
|
}
|
|
// TODO 1 从二级域名解构租户ID
|
|
const domain = window.location.hostname;
|
|
const parts = domain.split('.');
|
|
const subDomain = parts[0];
|
|
if (isInteger(subDomain)) {
|
|
console.log(`${subDomain}`)
|
|
// options.headers.tenantid = `${subDomain}`;
|
|
}
|
|
// TODO 2 从绑定域名解构的租户ID
|
|
// options.headers.tenantid = `5`;
|
|
if(localStorage.getItem('TenantId')){
|
|
options.headers.tenantid = `${localStorage.getItem('TenantId')}`;
|
|
}
|
|
},
|
|
onResponse({ response }) {
|
|
if (+response.status === 0 && +response._data.code !== 0) {
|
|
process.client && ElMessage.error(response._data.message);
|
|
}
|
|
if(+response.status === 500){
|
|
ElMessage.error('网络请求错误')
|
|
}
|
|
return response._data.data;
|
|
},
|
|
onResponseError({ response }) {
|
|
process.client &&
|
|
ElMessage.error(isArray(response._data.data.message) ? response._data.data.message[0] : response._data.data.message);
|
|
}
|
|
};
|
|
// console.log('请求接口:', baseUrl.value+url)
|
|
return useFetch<T>(url, { ...defaultOptions, ...opts } as any);
|
|
};
|