123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- import {
- AxiosConfig,
- AxiosResponse,
- AxiosRequestHeaders,
- AxiosError,
- InternalAxiosRequestConfig
- } from './types'
- import { ElMessage, ElMessageBox } from 'element-plus'
- import qs from 'qs'
- import { useStorage } from '@/hooks/web/useStorage'
- import { useTagsViewStore } from '@/store/modules/tagsView'
- import { resetRouter } from '@/router'
- import router from '@/router'
- const { getStorage, clear } = useStorage()
- const tagsViewStore = useTagsViewStore()
- const config: AxiosConfig = {
- /**
- * api请求基础路径
- */
- baseUrl: {
- // 开发环境接口前缀
- base: '',
- // 打包开发环境接口前缀
- dev: '',
- // 打包生产环境接口前缀
- pro: '',
- // 打包测试环境接口前缀
- test: ''
- },
- /**
- * 接口成功返回状态码
- */
- code: '200',
- /**
- * 接口请求超时时间
- */
- timeout: 60000,
- /**
- * 默认接口请求类型
- * 可选值:application/x-www-form-urlencoded multipart/form-data
- */
- defaultHeaders: 'application/x-www-form-urlencoded',
- interceptors: {
- //请求拦截
- // requestInterceptors: (config) => {
- // return config
- // },
- // 响应拦截器
- // responseInterceptors: (result: AxiosResponse) => {
- // return result
- // }
- }
- }
- const defaultRequestInterceptors = (config: InternalAxiosRequestConfig) => {
- if (
- config.method === 'post' &&
- (config.headers as AxiosRequestHeaders)['Content-Type'] === 'application/x-www-form-urlencoded'
- ) {
- config.data = qs.stringify(config.data)
- }
- if (config.method === 'get' && config.params) {
- let url = config.url as string
- url += '?'
- const keys = Object.keys(config.params)
- for (const key of keys) {
- if (config.params[key] !== void 0 && config.params[key] !== null) {
- url += `${key}=${encodeURIComponent(config.params[key])}&`
- }
- }
- url = url.substring(0, url.length - 1)
- config.params = {}
- config.url = url
- }
- if (getStorage('token')) {
- config.headers.token = getStorage('token')
- }
- return config
- }
- ;(error: AxiosError) => {
- Promise.reject(error)
- }
- const defaultResponseInterceptors = (response: AxiosResponse<any>) => {
- if (response?.config?.responseType === 'blob') {
- // 如果是文件流,直接过
- return response
- } else if (response.data.code === config.code) {
- return response.data
- } else if (response.data.code === 'A0000A') {
- ElMessageBox.alert(response.data.message, '提示', {
- showClose: false,
- callback: () => {
- clear()
- tagsViewStore.delAllViews()
- resetRouter() // 重置静态路由表
- router.replace('/login')
- }
- })
- } else {
- ElMessage.error(response.data.message)
- }
- }
- ;(error: AxiosError) => {
- console.log('err' + error) // for debug
- ElMessage.error(error.message)
- return Promise.reject(error)
- }
- export { defaultResponseInterceptors, defaultRequestInterceptors }
- export default config
|