fetch-api.js 5.65 KB
import axiosIns from 'axios';
import state from '@/store/state.js';
import CryptoJS from "crypto-js";
import JsEncrypt from "jsencrypt";

let key = process.env.VUE_APP_CONTENT_ENCRYPT_KEY;
let encryptSwitch = process.env.VUE_APP_CONTENT_ENCRYPT_SWITCH;
let rsa = new JsEncrypt();
rsa.setPublicKey(key);
let chars = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z".split(",");

function randomAesKey() {
	let res = "";
	for (let i = 0; i < 16; i++) {
		let id = Math.ceil(Math.random() * (chars.length - 1));
		res += chars[id];
	}
	return res;
};

function encryptContent(obj) {
	let aesKey = randomAesKey();
	let key = CryptoJS.enc.Utf8.parse(aesKey);
	var encrypted = CryptoJS.AES.encrypt(JSON.stringify(obj), key, {
		mode: CryptoJS.mode.ECB,
		padding: CryptoJS.pad.Pkcs7
	});
	let content = encrypted.toString(); //返回的是base64格式的密文
	let securityKey = rsa.encrypt(aesKey);

	let result = {
		k: securityKey,
		v: content
	};
	return result;
};

// import {
//   Toast
// } from 'vant';

function Toast(msg) {
	console.log("msg:", msg);
}

// axios的默认url
// axios.defaults.baseURL = ""

// 服务器地址
// let base = process.env.REQUEST_DOMAIN || "http://localhost:9101";
// let base = COM.baseUrl;
// console.log(process.env);
let base = "";
const axios = axiosIns.create({
	baseURL: process.env.VUE_APP_BASE_URL,
	timeout: 5000
})

let encryptPattern = [
	/^\/pingan_hklife_webapi\/policy.*/,
	/^\/pingan_hklife_webapi\/user.*/,
	/^\/pingan_hklife_webapi\/auth.*/,
	/^\/pingan_hklife_webapi\/customService.*/,
	/^\/pingan_hklife_webapi\/reset.*/,
]

let encryptWhileList = [
	"/pingan_hklife_webapi/policy/idPicUpload"
]

// 请求拦截器
axios.interceptors.request.use(
	config => {
		if (encryptSwitch == "true") {
			for (let index = 0; index < encryptPattern.length; index++) {
				let element = encryptPattern[index];
				if (element.test(config.url)) {
					if (encryptWhileList.indexOf(config.url) >= 0) {
						break;
					}
					let data = config.data;
					try {
						config.data = encryptContent(data);
					} catch (e) {
						console.error(e);
					}
					break;
				}
			}
		}
		return config;
	},
	error => {
		return Promise.error(error);
	})

// 响应拦截器
axios.interceptors.response.use(
	response => {
		if (response.status === 200) {
			if (response.data.code === 200) {
				return Promise.resolve(response);
			} else {
				// Toast(response.data.bizMsg);
				return Promise.reject(response.data);
			}
		} else {
			return Promise.reject(response.data);
		}
	},
	// 服务器状态码不是200的情况
	error => {
		if (error.response.status) {
			switch (error.response.status) {
				// 401: 未登录
				// 未登录则跳转登录页面,并携带当前页面的路径
				// 在登录成功后返回当前页面,这一步需要在登录页操作。
				case 401:
					router.replace({
						path: '/login',
						query: {
							redirect: router.currentRoute.fullPath
						}
					});
					break;
				// 403 token过期
				// 登录过期对用户进行提示
				// 清除本地token和清空vuex中token对象
				// 跳转登录页面
				case 403:
					Toast({
						message: '登录过期,请重新登录',
						duration: 1000,
						forbidClick: true
					});
					// 清除token
					localStorage.removeItem('token');
					store.commit('loginSuccess', null);
					// 跳转登录页面,并将要浏览的页面fullPath传过去,登录成功后跳转需要访问的页面
					setTimeout(() => {
						router.replace({
							path: '/login',
							query: {
								redirect: router.currentRoute.fullPath
							}
						});
					}, 1000);
					break;
				// 404请求不存在
				case 404:
					Toast({
						message: '网络请求不存在',
						duration: 1500,
						forbidClick: true
					});
					break;
				// 其他错误,直接抛出错误提示
				default:
					Toast({
						message: error.response.data.message,
						duration: 1500,
						forbidClick: true
					});
			}
			return Promise.reject(error.response);
		}
	}
);

//formDataHeaders设置
let formDataHeaders = {
	headers: {
		"Content-Type": "multipart/form-data"
	}
}

/**
 * 封装get方法
 * @param {*} params
 */
export const httpGet = params => {
	let {
		url,
		data,
		sid
	} = params;
	let headers = {};
	if (sid) {
		let sessionId = state.userInfo && state.userInfo.sid ? state.userInfo.sid : "";
		headers = {
			headers: {
				sid: sessionId
			}
		}
	}
	return axios.get(`${base}${url}`, {
		params: data
	}, headers).then(res => res.data.content);
}

/**
 * 封装post方法
 * @param {*} params
 */
export const httpPost = params => {
	let {
		url,
		data,
		sid,
		sidStr,
	} = params;
	let headers = {};
	if (sid) {
		let sessionId = state.userInfo && state.userInfo.sid ? state.userInfo.sid : "";
		headers = {
			headers: {
				sid: sessionId
			}
		}
	}
	if (sidStr) {
		headers = {
			headers: {
				sid: sidStr
			}
		}
	}
	return axios.post(`${base}${url}`, data, headers).then(res => res.data.content);
}

/**
 * 封装post方法
 * @param {*} params
 * data数据是 formdata格式
 * 例如:
 *          this.file = file
            let data = new FormData() //使用formData对象
            data.append('path', '/pro/mzczcradmin/')
            data.append('file', file.file)
 */
export const formdata = params => {
	let {
		url,
		data,
		sid,
	} = params;
	let headers = {
		headers: {
			"Content-Type": "multipart/form-data"
		}
	}
	let formData = new FormData(); //使用formData对象
	for (let key in data) {
		formData.append(key, data[key]);
	}
	if (sid) {
		let sessionId = state.userInfo && state.userInfo.sid ? state.userInfo.sid : "";
		headers.headers.sid = sessionId;
	}
	return axios.post(`${base}${url}`, formData, headers).then(res => res.data);
}