Vue3 的 axios封装
import axios, { AxiosPromise, AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import qs from 'qs'
import { Toast } from 'vant'
import { encrypt, decrypt } from './index'
import { IParamsType } from '@/types/interface'
type IAxiosResponse<T> = {
errorCode: string;
errorMsg: string;
returnCode: string;
returnMessage: string;
data: T;
}
export class Http {
service: AxiosInstance;
constructor() {
console.log(`constructor构造函数中的this:${this}`)
const errorCreate = (msg: string) => {
const err = new Error(msg)
if (process.env.NODE_ENV === 'development') {
console.log(err)
}
Toast.fail(err.message)
throw err
}
this.service = axios.create({
baseURL: process.env.VUE_APP_BASE_API,
timeout: 12000
})
this.service.interceptors.request.use((config: AxiosRequestConfig) => {
config.data.body = encrypt(JSON.stringify(config.data.body))
config.data = JSON.stringify(config.data)
return config
}, error => {
console.log(error)
return Promise.reject(error)
})
this.service.interceptors.response.use(
(response: AxiosResponse<any>): any => {
try {
response.data.body = JSON.parse(decodeURIComponent(decrypt(response.data.body)))
} catch (error) {
response.data.body = JSON.parse(decrypt(response.data.body))
}
const data = response.data.body
const t = { ...data }
const responseData = {
errorCode: data.errorCode,
errorMsg: data.errorMsg,
returnCode: data.returnCode,
returnMessage: data.returnMessage,
data: t
}
const { returnCode } = data
if (!returnCode || returnCode === undefined) {
errorCreate(`${data.errorMsg}: ${response.config.url}`)
return false
}
console.log('--------data:', data)
console.log('☞☞☞☞☞☞☞☞responseData:', responseData)
return responseData
},
error => {
if (error && error.response) {
switch (error.response.status) {
case 400:
error.message = '请求错误'
break
case 401:
error.message = '未授权,请登录'
break
case 403:
error.message = '拒绝访问'
break
case 404:
error.message = `请求地址出错: ${error.response.config.url}`
break
case 408:
error.message = '请求超时'
break
case 500:
error.message = '服务器内部错误'
break
case 501:
error.message = '服务未实现'
break
case 502:
error.message = '网关错误'
break
case 503:
error.message = '服务不可用'
break
case 504:
error.message = '网关超时'
break
case 505:
error.message = 'HTTP版本不受支持'
break
default:
break
}
}
return Promise.reject(error)
}
)
}
Post<T>(url: string, params: IParamsType, config: AxiosRequestConfig = {}): Promise<IAxiosResponse<T>> {
const _config = {
method: 'post',
url,
data: { header: { transCode: params.transCode }, body: { ...params } },
headers: {
'Content-Type': 'text/plain;charset=UTF-8'
}
}
config = Object.assign(_config, config)
return this.service(config)
}
Get<T>(url: string, params?: IParamsType, config = {}): Promise<IAxiosResponse<T>> {
const _config = {
method: 'get',
url: url,
params: params,
headers: {
'Content-Type': 'text/plain;charset=UTF-8'
},
paramsSerializer: function (params: IParamsType) {
return qs.stringify(params, { arrayFormat: 'repeat' })
}
}
config = Object.assign(_config, config)
return this.service(config)
}
Json(url: string, params: IParamsType, config = {}): AxiosPromise {
const _config = {
method: 'post',
url: url,
data: params,
headers: {
'Content-Type': 'application/json'
}
}
config = Object.assign(_config, config)
return this.service(config)
}
}
export default new Http()
import CryptoJS from 'crypto-js'
const KEY = CryptoJS.enc.Utf8.parse('202106011234567')
export const encrypt = (s: string, keyStr?: string): string => {
const key = (keyStr && CryptoJS.enc.Utf8.parse(keyStr)) || KEY
const encrypt = CryptoJS.enc.Utf8.parse(s)
const encrypted = CryptoJS.AES.encrypt(encrypt, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
})
return encrypted.toString()
}
export const decrypt = (s: string, keyStr?: string): string => {
const key = (keyStr && CryptoJS.enc.Utf8.parse(keyStr)) || KEY
const decrypted = CryptoJS.AES.decrypt(s, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
})
return CryptoJS.enc.Utf8.stringify(decrypted).toString()
}
export function setLocal(key: string, val: any) {
window.localStorage.setItem(key, encrypt(JSON.stringify(val)))
}
export function getLocal(key: string) {
return JSON.parse(decrypt(window.localStorage.getItem(key) as string))
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了