You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
72 lines
1.6 KiB
Plaintext
72 lines
1.6 KiB
Plaintext
11 months ago
|
import axios from 'axios'
|
||
|
import { useUserStore } from '@/stores/user'
|
||
|
const { VITE_GLOB_API_URL } = import.meta.env
|
||
|
const service = axios.create({
|
||
|
baseURL: import.meta.env.MODE === 'development' ? '/api' : VITE_GLOB_API_URL,
|
||
|
withCredentials: true
|
||
|
})
|
||
|
|
||
|
// 请求拦截
|
||
|
service.interceptors.request.use(
|
||
|
(config) => {
|
||
|
const user = useUserStore()
|
||
|
let url = config.url
|
||
|
if (config.params) {
|
||
|
if (!config.params.Token) config.params.Token = user.getToken
|
||
|
url += '?'
|
||
|
const keys = Object.keys(config.params)
|
||
|
for (const key of keys) {
|
||
|
try {
|
||
|
url += `${key}=${decodeURIComponent(config.params[key])}&`
|
||
|
} catch (e) {
|
||
|
throw new Error('不受支持的字符')
|
||
|
}
|
||
|
}
|
||
|
url = url?.substring(0, url?.length - 1)
|
||
|
config.params = {}
|
||
|
}
|
||
|
|
||
|
config.url = url
|
||
|
// config.headers = {
|
||
|
// 'Content-Type': 'multipart/form-data',
|
||
|
// };
|
||
|
return config
|
||
|
},
|
||
|
(error) => {
|
||
|
console.error(error)
|
||
|
return Promise.reject(error)
|
||
|
}
|
||
|
)
|
||
|
|
||
|
service.interceptors.response.use(
|
||
|
async (response) => {
|
||
|
const { data } = response
|
||
|
const { code, msg } = data;
|
||
|
if(code !== 200) {
|
||
|
return Promise.reject(msg)
|
||
|
}
|
||
|
const isJSON = await isJson(data.data);//判断返回的data是字符串还是成功信息
|
||
|
if(isJSON == true){
|
||
|
const res = JSON.parse(data.data);
|
||
|
return res;
|
||
|
}else{
|
||
|
return data;
|
||
|
}
|
||
|
|
||
|
},
|
||
|
(error) => {
|
||
|
return Promise.reject(error)
|
||
|
}
|
||
|
)
|
||
|
|
||
|
export default service
|
||
|
|
||
|
const isJson = async (str:string) =>{
|
||
|
try{
|
||
|
JSON.parse(str);
|
||
|
return true;
|
||
|
}catch(e){
|
||
|
return false;
|
||
|
}
|
||
|
}
|