import axios from 'axios'
axios.defaults.timeout = 10000
// 排序等封装办法
import myUtil from '../../lib/myutils.js';
// 引入 rsa 私钥
import rsakey from '../../lib/encrypt/rsakey.js'
// 引入 aes/rsa 加密配置文件
import Utils from "../../lib/encrypt/utils.js";
class HttpClient {constructor(baseUrl = process.env.VUE_APP_BASE_API) {this.baseUrl ='http://192.168.2.666/uc/'}
interceptors(instance) {
// 申请拦挡
instance.interceptors.request.use((config) => {if (config.data) {
// 参数非空过滤, 排序, 拼接成字符串
var backData = myUtil.ruleParams(config.data)
config.data = backData.fliterDta
// AES 密钥 (aesKey) 随机生成字符串
var myAesKey = myUtil.randomWord(false, 32); //32 位
// aesParams 应用 AES 加密申请参数
var aesParams = Utils.encrypt(JSON.stringify(config.data), myAesKey); //
config.data = {}
config.data['requestData'] = aesParams
//AES 加密后的 AES 密钥(aesKey), 应用 rsa 私钥加密 aes 密钥
let rsaAesKey = Utils.JSEncryptCommon(rsakey.rsakey,
myAesKey);
//Vue.$encryptedData(rsakey.rsakey, myAesKey); //myAesKey 解密前应用 base64 转字符串 // ----- ok
var baseRsaAesKey = rsaAesKey; // 编码
config.data['sign'] = baseRsaAesKey
return config
}
return config
},
(error) => Promise.reject(error.response)
)
// response 拦截器
instance.interceptors.response.use((response) => {
// 解密
if (response.data.responseData && response.data.sign) {
// 1.res 解出 aes 秘钥
var aesKey = Utils.JSDecryptCommon(response.data.sign)
// 2.aes 解出返回数据
var parseData = Utils.decrypt(response.data.responseData, aesKey)
parseData = JSON.parse(parseData)
var myres = {data: parseData}
const {data} = myres
const {code} = data
if (data && (code === 0 || code === 4000)) return data
return Promise.reject(myres)
} else {const { data} = response
const {code} = data
if (data && (code === 0 || code === 4000)) return data
return Promise.reject(response)
}
},
(error) => Promise.reject(error)
)
}
getDefaultOptions() {
const config = {
baseURL: this.baseUrl,
timeout: 10 * 1000, // 申请超时工夫
withCredentials: false,
headers: {}}
return config
}
request(options) {const instance = axios.create()
options = Object.assign(this.getDefaultOptions(), options)
this.interceptors(instance, options.url)
return instance(options)
}
// 下载接口
getDefaultOptionsD() {
const config = {
baseURL: 'https://api-test.baidu.com',
timeout: 10 * 1000, // 申请超时工夫
withCredentials: false,
headers: {}}
return config
}
requestD(options) {const instance = axios.create()
options = Object.assign(this.getDefaultOptionsD(), options)
this.interceptors(instance, options.url)
return instance(options)
}
}
export default new HttpClient()