爱山东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.

116 lines
3.5 KiB

3 months ago
import axios from 'axios'
3 months ago
import type { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse} from 'axios' //, InternalAxiosRequestConfig
3 months ago
import { Message } from '@arco-design/web-vue'
import serviceUrls from '@/config/baseUrlConfig'
// 数据返回的接口
// 定义请求响应参数,不含data
interface Result {
code: number
msg: string
}
// 请求响应参数,包含data
interface ResultData<T = any> extends Result {
data?: T
}
3 months ago
const URL: string = serviceUrls.baseService
3 months ago
enum RequestEnums {
TIMEOUT = 20000,
OVERDUE = 600, // 登录失效
FAIL = 999, // 请求失败
SUCCESS = 200, // 请求成功
}
const config = {
// 默认地址
baseURL: URL as string,
// 设置超时时间
timeout: RequestEnums.TIMEOUT as number,
// 跨域时候允许携带凭证
withCredentials: true,
}
class RequestHttp {
// 定义成员变量并指定类型
service: AxiosInstance
public constructor(config: AxiosRequestConfig) {
// 实例化axios
this.service = axios.create(config)
/**
*
* -> [] ->
* token校验(JWT) : token,vuex/pinia/
*/
3 months ago
// this.service.interceptors.request.use(
// (config: InternalAxiosRequestConfig) => {
// config.headers['Authorization'] = localStorage.getItem('token') || ''
// return config
// },
// (error: AxiosError) => {
// // 请求报错
// Promise.reject(error)
// }
// )
3 months ago
/**
*
* -> [] -> JS获取到信息
*/
this.service.interceptors.response.use(
(response: AxiosResponse) => {
const { data, config } = response // 解构
if (data.code === RequestEnums.OVERDUE) {
// 登录信息失效,应跳转到登录页面,并清空本地的token
localStorage.setItem('token', '')
return Promise.reject(data)
}
// 全局错误信息拦截(防止下载文件得时候返回数据流,没有code,直接报错)
if (data.code && data.code !== RequestEnums.SUCCESS) {
2 months ago
Message.error(data.msg) // 此处也可以使用组件提示报错信息
3 months ago
return Promise.reject(data)
}
return data
},
(error: AxiosError) => {
const { response } = error
if (response) {
this.handleCode(response.status)
}
if (!window.navigator.onLine) {
Message.error('网络连接失败')
// 可以跳转到错误页面,也可以不做操作
// return router.replace({
// path: '/404'
// });
}
}
)
}
handleCode(code: number): void {
switch (code) {
case 401:
Message.error('登录失败,请重新登录')
break
default:
Message.error('请求失败')
break
}
}
// 常用方法封装
get<T>(url: string, params?: object): Promise<ResultData<T>> {
return this.service.get(url, { params })
}
post<T>(url: string, params?: object): Promise<ResultData<T>> {
return this.service.post(url, params)
}
put<T>(url: string, params?: object): Promise<ResultData<T>> {
return this.service.put(url, params)
}
delete<T>(url: string, params?: object): Promise<ResultData<T>> {
return this.service.delete(url, { params })
}
}
// 导出一个实例对象
export default new RequestHttp(config)