fetch-api.js 6.43 KB
import axiosIns from 'axios';
import state from '@/store/state.js';
import { SET_USER_INFO } from '@/store/mutations.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(",");
// 生成随机AES秘钥
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;
};

/**
 * 对内容进行加密
 * 结构约定为 {k,v}
 * @param {*} obj
 */
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;
};

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


// 服务器地址
// let base = process.env.REQUEST_DOMAIN || "http://localhost:9101";
// let base = COM.baseUrl;
// console.log(process.env);
let baseURL = process.env.VUE_APP_BASE_URL;
// baseURL = "http://localhost:9101";
// if (window.location.href.indexOf("192.168") != -1) {
// 	baseURL = "https://ow.go.qudone.com";
// }
const axios = axiosIns.create({
	baseURL: baseURL,
	timeout: 10000
})

// 加密模式
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",
	"/pingan_hklife_webapi/policy/updateIdFileV2",
	"/pingan_hklife_webapi/policy/clarmsUpload",
	"/pingan_hklife_webapi/policy/upload/file/iobs",
]

// 请求拦截器
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 {
				if (response.data.code === 404) {
					SET_USER_INFO(state, null);
					for (let index = 0; index < sessionStorage.length; index++) {
						let key = sessionStorage.key(index);
						sessionStorage.removeItem(key);
					}
				}
				// 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(`${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(`${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,
		myFormData,
		sid,
	} = params;
	let headers = {
		headers: {
			"Content-Type": "multipart/form-data"
		}
	}
	let lastFormData = null
	if (data) {
		lastFormData = new FormData(); //使用formData对象
		for (let key in data) {
			lastFormData.append(key, data[key]);
		}
	} else {
		lastFormData = myFormData;
	}
	if (sid) {
		let sessionId = state.userInfo && state.userInfo.sid ? state.userInfo.sid : "";
		headers.headers.sid = sessionId;
	}
	return axios.post(`${url}`, lastFormData, headers).then(res => res.data);
}

export const requestDomain = () => {
	return baseURL;
}