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.

97 lines
2.5 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

function transform(error: any) {
console.error('error', error)
const err = (text: string) => {
ElMessage.error(error?.response?._data.message ?? text);
};
if (error?.response?._data) {
switch (error.response.status) {
case 404:
err("服务器资源不存在");
break;
case 500:
err("服务器内部错误");
break;
case 401:
// 清除缓存
err("登录状态已过期,需要重新登录");
// TODO 跳转到登录界面
break;
case 403:
err("没有权限访问该资源");
break;
default:
err(error.response._data.msg);
}
} else {
err("请求超时,服务器无响应!");
}
}
console.log($fetch)
/**
* api请求封装
* @param { String } url 请求地址
* @param { Object } options useFtech第二个参数
* @param { Object } headers 自定义header头, 单独设置headers区分请求参数也好设置类型
*/
const fetch = $fetch.create({
async onRequest({options}){
options.baseURL = '/api';
const token = useUserInfo().$state.token;
console.log('options>>>', options)
options.headers = new Headers(options.headers);
if (token) {
options.headers.set('token', token)
}
},
// 响应拦截
onResponse(ctx) {
const {response} = ctx;
let data = response._data;
// 在这里判断错误
if (data.code != 1) {
transform(ctx)
return Promise.reject(ctx)
}
// 成功返回
return data;
},
// 错误处理
onResponseError(error) {
transform(error)
return Promise.reject(error?.response?._data ?? null);
}
})
export default class Http<T> {
contact(...params: string[]) {
console.log('params>>>>', params)
return params.join('')
}
toFormData(data: { [x: string]: any; }) {
const dataParams = new FormData();
for (const dataKey in data) {
dataParams.append(dataKey, data[dataKey])
}
return dataParams
}
get(url: string, params?: any, headers?: any) {
console.log('url>>>>', url)
return fetch<T>(url, {method: 'get', params, headers})
}
post(url: string, data?: any, headers?: any) {
return fetch<T>(url, {method: 'post', body:data, headers})
}
put(url: string, params?: any, headers?: any){
return fetch<T>(url, {method: 'put', body:params, headers})
}
delete(url: string, params?: any, headers?: any) {
return fetch<T>(url, {method: 'delete', body:params, headers})
}
}